在下面的代码,为什么所有三个IntComparator(),IntComparator2和IntComparator3工作为的第三个参数sort()的功能?它们不会具有不同的l值函数类型吗?基于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;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
std::sort接受一个functor。这是可以调用的任何对象(带有正确的参数)。该函数通过使用模板来实现此目的,如下所示
template<typename Iter, typename Comp>
void sort(Iter begin, Iter end, Comp compare) { ... }
Run Code Online (Sandbox Code Playgroud)
IntComparator1,2和3都是此比较器的有效函子,因为它们都可以使用带有2个整数的operator()来调用。
也就像您说的那样,第三个选项通常确实更直观。