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())?

Anton Krug
  • 1,333
  • 2
  • 16
  • 31

0 Answers0