-2

Suppose I have a vector of pair container:

vector <pair <int, int>> vp = {{1, 2}. {4, 4}, {2, 3}};

Now I want to sort this container in acsending order using sort function:

sort(vp.begin(), vp.end());

Output:

{{1, 2}, {2, 3}, {4, 4}}

Now my question is that how the function works in-depth.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • it has nothing to do with `std::sort` but the [`operator<`](https://en.cppreference.com/w/cpp/utility/pair/operator_cmp) in [`std::pair`](https://en.cppreference.com/w/cpp/utility/pair) which does [lexicographic comparison](https://en.wikipedia.org/wiki/Lexicographic_order) – phuclv Mar 28 '22 at 07:49
  • duplicates: [How does std::sort work for list of pairs?](https://stackoverflow.com/q/23816797/995714), [Is std::pair ordering well-defined?](https://stackoverflow.com/q/2819245/995714) – phuclv Mar 28 '22 at 07:52

2 Answers2

2

It sorts in accordance with the ordering of std::pair<int, int> class, which compares the first elements, and if they are equivalent, then compares the second elements. What algorithm is actually used to sort the vector is implementation-defined. Typically it is a mixture of a number of algorithms to adapt to different situations (number of elements, etc.).

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
1

std::sort uses the elements operator< when not other comparator used. std::sort may use any sorting algorithm that meets the specification, most importantly the number of comparisons is of O(N·log(N)), where N = std::distance(first, last).

std::pair<T1,T2>::operator< compares first and only if they are equivalent compares their second.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185