Map C++ Sort and Insert elements by value

This is not possible in C++ to sort map based on its values due to its internal implementation.
Map sorts elements only based on its key.

But there is a way you can achieve what you want.(Both needs additional space though.)

1) If you only want all the values to be sorted & not needing their mapping. You can put all the keys in a vector and then sort the vector.

2) And suppose you want that mapping too. Then you can create a vector of pair<> and then define a comparator to sort based on second value of pair.

bool sortBySecond(const pair<int, int> &a, const pair<int, int> &b){
    return (a.second < b.second);
}

Inside main:

vector<pair<int, int> > vect;
sort(vect.begin(), vect.end(), sortBySecond);

The above vector will have pair sorted on the basis of your values of map in ascending order.

Leave a Comment