'why sort stl in c++, sort on the basis of first value of vector of pairs in cpp [duplicate]

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.



Solution 1:[1]

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.).

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ayxan Haqverdili
Solution 2 463035818_is_not_a_number