0

When I want to sort a vector of something I can provide my own comparison function like here:

https://stackoverflow.com/a/14419565/4535300

So in my example the nested array contains only 2 entries and I can provide my own custom lambda comparison function that it will sort by the very first entry of the nested array:

std::vector<std::vector<int>> input({{34335,39239},{15875,91969},{29673,66453},{53548,69161},{40618,93111}});

std::sort(input.begin(), input.end(), [] (const std::vector<int>& a, const std::vector<int>& b) { return a[0]<b[0];});
//  std::sort(input.begin(), input.end());

for (const auto &i:input) {
    std::cout << i[0] << "-" << i[1] << " ";
}
std::cout << std::endl;

And the result get sorted as I want, what I do not 100% fully understand, how this can work the same without the comparison function as the std::sort(input.begin(), input.end()) will produce the same result.

What I think is happening, is that the sorting algorithm uses the operator< as stated here: https://www.cplusplus.com/reference/algorithm/sort/

And vector uses the relational_operators overloads: https://www.cplusplus.com/reference/vector/vector/operators/ and operator< should be doing lexicographical_compare.

And that is allowing me to get the same results in my very specific example (and very specific input data) even when I'm using std::sort(input.begin(), input.end())?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
Anton Krug
  • 1,555
  • 2
  • 19
  • 32
  • 2
    Yeah, your reasoning sounds right. – cigien Feb 20 '22 at 14:01
  • 2
    You may observe the difference if you try it with pairs where the first component is equal but the second is different. The library-provided `operator<` would use the second component to break ties, whereas your comparison declares such pairs equivalent, so they'd be sorted in some unpredictable order. – Igor Tandetnik Feb 20 '22 at 14:53

0 Answers0