在下面的代码中,为什么这三个IntComparator()
, IntComparator2
and IntComparator3
作为第三个参数sort()
功能?他们不会有不同的左值函数类型吗?基于https://en.cppreference.com/w/cpp/algorithm/sort it says
比较函数的签名应该等于
下列的:
bool cmp(const Type1 &a, const Type2 &b);
这似乎匹配IntComparator2
better?
另外哪一个更可取?第三个选项似乎更简单、更直观。
#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;
}