c++ - 排序比较功能奇怪的行为

标签 c++ sorting

下面的函数是我的比较函数。虽然直接比较两个字符成功地对数组进行了分类,但使用 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/

相关文章:

c++ - 如何通过函数模板参数化函数?

具有唯一键的排序对列表的 Java 结构建议

JavaScript 按嵌套对象降序对数组进行排序

c++ - 将对值分配给映射键时出错

java - 对已排序的列表进行排序时,列表迭代在 Java 8 中抛出 ConcurrentModificationException

c++ - 具有自定义比较函数结果错误的 std::sort 函数:必须调用对非静态成员函数的引用

java - 对数组进行降序排序,并将主数组的变化收集到新数组中

c++ - open ofstream 作为类属性

c++ - 如何知道线程上下文切换何时发生?

未调用 C++/CX D'tor