How to sort elements of pairs inside vector?

You just:

std::sort(v.begin(), v.end());

std::pair is lexicographically compared.

On the other hand if you want to sort them with respect the second element of the std::pair then you would have to defind a custom comparator in the following manner:

std::sort(v.begin(), v.end(), [](std::pair<int, std::string> const &p1,
                                 std::pair<int, std::string> const &p2) { 
                                   return (p1.second == p2.second)?
                                             p1.first < p2.first  :
                                             p1.second < p2.second;

Browse More Popular Posts

Leave a Comment