在下面的代码中,为什么所有三个
此外,哪种方法更可取?第三个选项似乎更简单直观。
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;
}
comp
不会通过解引用的迭代器应用任何非常量函数。”你可能可以使用bool IntComparator3 (int &a, int &b)
,但如果a
或b
被修改,则行为未定义。 - Caleth