Why std :: sort doesn't use my operator <implementation

Why std :: sort doesn't use operator< implementation in this code

 #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; } 

Output:

 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, 

Expected Result:

 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, 
+7
source share
1 answer

This is due to how name lookups work in function templates (usually called two-phase lookups). std::sort defined in <algorithm> , and a search for < will find these names in scope at the template definition point (and this is not yours), and those names in the associated namespaces of the function's dependent arguments (which for std::tuple will be namespace std , which also does not include yours).

Since the arguments in question are in the std , this is actually undefined behavior to add your overload to this namespace. Thus, your options should either adhere to the default behavior (which will be lexicographical < ), or provide your own custom comparator (as in your question).

+9
source

All Articles