How to Sort Map by Value in C++: Simple Guide
In C++, you cannot directly sort a
std::map by its values because it sorts by keys by default. Instead, copy the map's key-value pairs into a std::vector of pairs and then sort this vector using a custom comparator that compares the values.Syntax
To sort a map by value, follow these steps:
- Copy the map elements into a
std::vector<std::pair<Key, Value>>. - Use
std::sortwith a custom comparator that compares the second element (value) of each pair. - Iterate over the sorted vector to access elements in value order.
cpp
std::map<Key, Value> myMap; std::vector<std::pair<Key, Value>> vec(myMap.begin(), myMap.end()); std::sort(vec.begin(), vec.end(), [](const auto &a, const auto &b) { return a.second < b.second; // sort by value ascending });
Example
This example shows how to sort a std::map<std::string, int> by its values in ascending order and print the sorted pairs.
cpp
#include <iostream> #include <map> #include <vector> #include <algorithm> int main() { std::map<std::string, int> myMap = { {"apple", 5}, {"banana", 2}, {"cherry", 7}, {"date", 3} }; // Copy map to vector std::vector<std::pair<std::string, int>> vec(myMap.begin(), myMap.end()); // Sort vector by value std::sort(vec.begin(), vec.end(), [](const auto &a, const auto &b) { return a.second < b.second; }); // Print sorted vector for (const auto &pair : vec) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }
Output
banana: 2
date: 3
apple: 5
cherry: 7
Common Pitfalls
Common mistakes when sorting a map by value include:
- Trying to sort the
std::mapdirectly, which is impossible because it is always sorted by keys. - Not copying elements to a vector first.
- Forgetting to use a custom comparator that compares the values (second element of pairs).
- Modifying the map while iterating over the sorted vector, which can cause inconsistencies.
cpp
/* Wrong approach: Trying to sort map directly (won't compile) */ // std::sort(myMap.begin(), myMap.end(), [](const auto &a, const auto &b) { // return a.second < b.second; // }); /* Correct approach: Copy to vector and sort */ std::vector<std::pair<Key, Value>> vec(myMap.begin(), myMap.end()); std::sort(vec.begin(), vec.end(), [](const auto &a, const auto &b) { return a.second < b.second; });
Quick Reference
Summary tips for sorting a map by value in C++:
- Use
std::vectorto hold map entries. - Sort with
std::sortand a lambda comparingpair.second. - Remember
std::mapitself cannot be reordered by value. - Use this method when you need ordered access by values.
Key Takeaways
You cannot sort a std::map by value directly because it sorts by keys.
Copy map entries into a std::vector of pairs to sort by value.
Use std::sort with a custom comparator comparing the second element of pairs.
Iterate over the sorted vector to access elements in value order.
Avoid modifying the map while using the sorted vector to prevent inconsistencies.