C++ 为什么';t std::排序使用我的运算符<;实施
为什么std::sort不使用myC++ 为什么';t std::排序使用我的运算符<;实施,c++,operator-overloading,C++,Operator Overloading,为什么std::sort不使用my操作符这与函数模板中名称查找的工作方式有关(通常称为两阶段查找)std::sort在中定义,并且的查找在移动自定义操作符后有效 #include <iostream> #include <vector> #include <tuple> #include <algorithm> using namespace std; bool operator<( const tuple<int, int&
操作符这与函数模板中名称查找的工作方式有关(通常称为两阶段查找)std::sort
在
中定义,并且的查找在移动自定义操作符后有效
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;
bool operator<(
const tuple<int, int>& t1,
const tuple<int, int>& t2
) {
return get<1>(t1) > get<1>(t2);// `>` so that it gets sorted in reverse
}
int main() {
vector<tuple<int, int>> v;
for (int i = 0; i < 10; ++i) {
v.push_back(make_tuple(0, i));
}
cout << "before sort: ";
for (auto& x : v) { cout << get<1>(x) << ", "; }
cout << endl;
auto v2 = v;
sort(v2.begin(), v2.end());
cout << "after sort(begin, end): ";
for (auto& x : v2) { cout << get<1>(x) << ", "; }
cout << endl;
sort(v.begin(), v.end(), [](auto& t1, auto& t2) {
return get<1>(t1) > get<1>(t2);// `>` so that it gets sorted in reverse
});
cout << "after sort(begin, end, comparator): ";
for (auto& x : v) { cout << get<1>(x) << ", "; }
cout << endl;
return 0;
}
before sort: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
after sort(begin, end): 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
after sort(begin, end, comparator): 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
before sort: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
after sort(begin, end): 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
after sort(begin, end, comparator): 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,