【发布时间】:2019-05-17 09:01:03
【问题描述】:
在下面的代码中,为什么IntComparator()、IntComparator2 和IntComparator3 这三个参数都作为sort() 函数的第三个参数工作?他们不会有不同的左值函数类型吗?基于https://en.cppreference.com/w/cpp/algorithm/sort 它说
比较函数的签名应该等同于 以下:
bool cmp(const Type1 &a, const Type2 &b);
似乎与IntComparator2 更匹配?
还有哪一个更可取?第三个选项似乎更简单、更直观。
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
struct IntComparator
{
bool operator()(const int &a, const int &b) const
{
return a < b;
}
};
bool IntComparator2 (const int &a, const int &b)
{
return a < b;
}
bool IntComparator3 (int a, int b)
{
return a < b;
}
int main()
{
int items[] = { 4, 3, 1, 2 };
std::sort(items, items+4, IntComparator());
for (int n=0; n<4; n++) {
std::cout << items[n] << ", ";
}
std::cout << "\n";
int items2[] = { 4, 3, 1, 2 };
std::sort(items2, items2+4, IntComparator2);
for (int n=0; n<4; n++) {
std::cout << items2[n] << ", ";
}
std::cout << "\n";
int items3[] = { 4, 3, 1, 2 };
std::sort(items3, items3+4, IntComparator3);
for (int n=0; n<4; n++) {
std::cout << items3[n] << ", ";
}
std::cout << "\n";
return 0;
}
【问题讨论】:
-
我只是在阅读上面给出的参考资料; 应该等价于的表述确实有些模棱两可。
-
@Codor 标准说“假定
comp不会通过取消引用的迭代器应用任何非常量函数。”您也许可以使用bool IntComparator3 (int &a, int &b),但如果a或b被它修改,这是未定义的行为 -
@Caleth 我们最近禁止了那个。