c++ - 字母排序是向后使用 string.compare()

标签 c++ string sorting linked-list alphabetical

我有一个函数,可以在字母表中的适当位置将单词添加到链表中。它应该按 A-Z 排序,但由于某种原因,它是相反的。我认为问题是我错误地使用了 string.compare() ,但也可能是其他原因。这可能是一个简单的修复,我只是盯着它看了一会儿,希望能有一个新的视角!

void LinkedList::addWord( const string& theWord )
{
    ListNode* toAdd = new ListNode(theWord, NULL);

    if( !mpHead ){
        mpHead = toAdd;
        return;
    }

    if(mpHead->word.compare(theWord) < 0){
        toAdd->pNextNode = mpHead;
        mpHead = toAdd;
        return;
    }

    if(mpHead->pNextNode == NULL){
        mpHead->pNextNode = toAdd;
        return;
    }

    ListNode* pCurrent = mpHead;
    ListNode* pCurrentNext = mpHead->pNextNode;

    while( pCurrent->pNextNode->word.compare(theWord) > 0 )
    {
        pCurrent = pCurrentNext;
        pCurrentNext = pCurrentNext->pNextNode;
    }

    toAdd->pNextNode = pCurrent->pNextNode;
    pCurrent->pNextNode = toAdd;
}

最佳答案

看来你已经交换了 compare 的参数.想到a.compare(b) < 0相当于a < b .然后你会看到你在做什么:

if (Head < theWord) { insert theWord before Head; }

你可能是说 if (theWord < Head)相反,所以真正的代码是:

if(theWord.compare(mpHead->word) < 0){
    toAdd->pNextNode = mpHead;
    mpHead = toAdd;
    return;
}

// ...

while( theWord.compare(pCurrent->pNextNode->word) > 0 )
{
    pCurrent = pCurrentNext;
    pCurrentNext = pCurrentNext->pNextNode;
}

当然,因为您只使用每个 compare() 的结果曾经,您可以使用 operator <直接代替:

if(theWord < mpHead->word)

//...

while( theWord > pCurrent->pNextNode->word)

关于c++ - 字母排序是向后使用 string.compare(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22563560/

相关文章:

c++ - 每 X 字节删除空字节 c++ WINAPI

python - 查找子序列(非连续的)

python - 一次替换 Pandas Series 的多个子字符串

android - 从 sqlite 按日期升序排序列表

javascript - 将数字的javascript数组拆分为范围

c# - 我如何使用 3d 变换计算 2d 边界框

c++ - 突然从 cython 中反复调用 c++ 方法要慢得多

c++ - 我应该上课而不是重复的 get/set 语句吗?

ios - if 语句不返回任何内容

swift - 带有两个键的核心数据 NSSortDescriptor