在下面的代码中,为什么 IntComparator()
、IntComparator2
和 IntComparator3
这三个都作为 的第三个参数排序()
函数?他们不会有不同的左值函数类型吗?基于https://en.cppreference.com/w/cpp/algorithm/sort它说
The signature of the comparison function should be equivalent to the following:
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;
}
最佳答案
std::sort
接受一个仿函数
。这是可以调用的任何对象(使用正确的参数)。该函数通过使用模板来实现这一点,如下所示
template<typename Iter, typename Comp>
void sort(Iter begin, Iter end, Comp compare) { ... }
IntComparator1
、2 和 3 都是此比较器的有效仿函数,因为它们都可以使用带有 2 个整数的 operator() 来调用。
也像你说的,第三种选择确实通常更直观。
关于c++ - std::sort 自定义比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56183031/