使用string.compare()进行反向字母排序
Alphabetical Sorting is backwards using string.compare()
我有一个函数,它将一个单词添加到字母表中适当位置的链表中。它应该按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)
直接使用std::set。
#include <set>
#include <string>
// ...
std::set<std::string> s;
s.insert("foo");
s.insert("fred");
// ...
with std::list(允许链表+副本):
#include <list>
#include <algorithm>
// ...
std::list<std::string> l;
l.insert(std::lower_bound(l.begin(), l.end(), "foo"), "foo");
l.insert(std::lower_bound(l.begin(), l.end(), "fred"), "fred");
l.insert(std::lower_bound(l.begin(), l.end(), "foo"), "foo");
// ...
注意:在
相关文章:
- 二叉排序树无法编译
- 将图形表示为unordered_map<字符串、向量>时拓扑排序错误<string>
- 为什么我的函数接受"std::string"进行排序不会改变它?
- 从映射<字符串、矢量中对唯一值进行排序<string>>
- 按值对 std::unordered_map<std:::string, std::atomic<unsigned int>> 进行排序
- 对 c++ 向量<string>进行排序
- 如何在 c 中比较和排序向量<string>
- C++ 将矢量的排序内容写入<string>文件
- c++STL通过int和string的向量进行排序
- std::sort 无法对 std::vector<std::string 的元素进行排序>
- <string> 设置像数字一样的排序
- 合并排序 std:string 中的字符
- 按值的降序对 C++ 中的 Map<string,int> 进行排序
- 如何使用选择排序对向量进行<string>排序
- 如何声明一个将string和int数组一起排序的函数?
- 如何用O(n)个时间和O(1)个空间对n个对象的群进行排序.每个对象有两个字段:int和string
- 使用自定义排序功能对向量<string>中的字符串进行排序时出现分段错误
- String对象数组的c++选择排序
- 如何根据要排序的向量中的向量对结构<string>向量进行排序?
- 使用string.compare()进行反向字母排序