How can I sort an STL map by value?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Sure, let's dive into sorting an STL map by its values, a common task when working with associative containers in C++. By default, an std::map
in C++ is sorted by its keys, which are unique and ordered according to the specified comparison function or operator, usually in ascending order. However, there are times when you might want to sort the map based on its values instead. Here's how you can achieve that effectively.
Understanding std::map
An std::map
is a key-value data structure where each key is unique. The elements in a map are always sorted by the keys. The keys provide an efficient way to retrieve values, making maps useful for fast lookups based on the key.
Key Characteristics of std::map
:
- Key Sorting: By default, it uses a balanced binary search tree to maintain order based on keys.
- Iterator Invalidation: Iterators remain valid unless the associated element is deleted.
Sorting a Map by Values
Since the values are not inherently sorted in an std::map
, sorting by values requires additional steps. The typical approach involves:
- Extracting key-value pairs into a sequence container such as
std::vector. - Sorting the vector based on the values.
- If needed, reconstructing the sequence back into a map-like structure.
Technical Explanation
Here's a step-by-step guide to sorting an std::map
by its values.
Step-by-step Code Explanation
- Transfer to Vector: This allows us to take advantage of
std::sort, which is not directly possible on maps. - **Lambda Function in
std::sort**: The lambda function denotes how pairs are compared. Here, it compares based on the second element, i.e., the value in the map. - Efficiency: Sorting with
std::sorthas a time complexity of , where is the number of elements. - Map Stability and Reuse: The sorted vector maintains the relationship between keys and values, but if you decide to re-map them, you'll need to ensure there are no duplicate keys unless using a multimap-like structure.
- Alternative Structures: For frequent or large sorts by value, consider using structures like
std::multimaporstd::vectorwith a custom struct.
Related reading
- How can I sort generic list DESC and ASC?
- How can I sort Map values by key in Java?
- How can I sort the values in a custom Keras / Tensorflow `Loss` Function?
- How can I tell if a string repeats itself in Python?
- How can I turn a List of Lists into a List in Java 8?
- How can I use a conditional expression expression with if and else in a list comprehension?
- How can I use something like stdvectorstdmutex?
- How can memory_order_relaxed work for incrementing atomic reference counts in smart pointers?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.