下面的函数是我的比较函数。虽然直接比较两个字符成功地对数组进行了分类,但使用 std::string 比较函数却没有。
int compare (student a, student b) {
return a.name.compare(b.name);
return a.name[0] < b.name[0];
}
电话
sort(data.begin(), data.end(), compare);
其中数据定义为 vector <student> data;
您知道为什么 std::compare 不对它进行排序吗?
PS: std::compare 导致反转位置,例如艾伦、理查德、拜伦、莎拉 -> 莎拉、拜伦、理查德、艾伦。
最佳答案
std::string::compare返回一个 int
,您要将其与 0
进行比较以给出实际的排序顺序。例如,要检查 a.name
是否小于 b.name
(根据 compare
给出的顺序),您可以这样写:
return a.name.compare(b.name) < 0;
您当前编写的方式将为任何不相等的字符串返回 true
,这不是有效的 strict weak ordering , 根据 std::sort 的要求.
这里根本没有理由使用compare
,因为std::string有一个 operator<给出了两个字符串的等效顺序:
return a.name < b.name;
关于c++ - 排序比较功能奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15373306/