Sort a map by values in C++

Google Translate Icon

This post will discuss how to sort a map by values in C++.

We know that the 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 function

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

Download  Run Code

Output:

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

2. Using std::set function

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 orders the pairs by their second value.

Download  Run Code

Output:

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

3. Using std::multimap function

Finally, we can also build another map that uses the original map’s values as keys and the 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}

That’s all about sorting a map by values in C++.

Rate this post

Average rating 3.71/5. Vote count: 35

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?




Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)



Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Do NOT follow this link or you will be banned from the site!