Sort a map by values in C++

In this post, we will discuss how to sort a map by values in C++.


 

We know that std::map container sorts its elements by keys by default and not by values. This post provides an overview of some of the available alternatives to accomplish this.

 

1. Using std::vector

The idea is to convert the std::map into a std::vector of key-value pairs and sort that vector according to increasing order of its pair’s second value.

 

Download   Run Code

Output:

{one,1}
{two,2}
{three,3}
{four,4}

 

2. Using std::set

We can also use std::set instead of std::map. The idea is to insert all the key-value pairs into a std::set constructed using a comparator that order the pairs by their second value.

 

Download   Run Code

Output:

{one,1}
{two,2}
{three,3}
{four,4}

 

3. Using std::multimap

Finally, we can also build another map that uses original map’s values as keys and original map’s keys as values. Of course, this will only work if all values in the original map are distinct. If values are not distinct, consider using a std::multimap instead.

 

Download   Run Code

Output:

{one,1}
{two,2}
{three,3}
{four,4}

 
1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Categories

Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
Dionysis
Guest

Great solutions 🙂