Skip to content
Related Articles
Sorting a Map by value in C++ STL
• Difficulty Level : Medium
• Last Updated : 31 May, 2020

Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key. Below is the various method to achieve this:

Method 1 – using the vector of pairs The idea is to copy all contents from the map to the corresponding vector of pairs and sort the vector of pairs according to second value using the lambda function given below:

```bool cmp(pair<T1, T2>& a,
pair<T1, T2>& b)
{
return a.second < b.second;
}

where T1 and T2
are the data-types
that can be the
same or different.
```

Below is the implementation of the above approach:

 `// C++ program for the above approach`` ` `#include ``using` `namespace` `std;`` ` `// Comparator function to sort pairs``// according to second value``bool` `cmp(pair& a,``         ``pair& b)``{``    ``return` `a.second < b.second;``}`` ` `// Function to sort the map according``// to value in a (key-value) pairs``void` `sort(map& M)``{`` ` `    ``// Declare vector of pairs``    ``vector > A;`` ` `    ``// Copy key-value pair from Map``    ``// to vector of pairs``    ``for` `(``auto``& it : M) {``        ``A.push_back(it);``    ``}`` ` `    ``// Sort using comparator function``    ``sort(A.begin(), A.end(), cmp);`` ` `    ``// Print the sorted value``    ``for` `(``auto``& it : A) {`` ` `        ``cout << it.first << ``' '``             ``<< it.second << endl;``    ``}``}`` ` `// Driver Code``int` `main()``{`` ` `    ``// Declare Map``    ``map M;`` ` `    ``// Given Map``    ``M = { { ``"GfG"``, 3 },``          ``{ ``"To"``, 2 },``          ``{ ``"Welcome"``, 1 } };`` ` `    ``// Function Call``    ``sort(M);``    ``return` `0;``}`
Output:
```Welcome 1
To 2
GfG 3
```

Method 2 – using the set of pairs The idea is to insert all the (key-value) pairs from the map into a set of pairs that can be constructed using a comparator function that orders the pairs according to the second value.

Below is the implementation of the above approach:

 `// C++ program for the above approach``#include ``using` `namespace` `std;`` ` `// Comparison function for sorting the``// set by increasing order of its pair's``// second value``struct` `comp {``    ``template` `<``typename` `T>`` ` `    ``// Comparator function``    ``bool` `operator()(``const` `T& l,``                    ``const` `T& r) ``const``    ``{``        ``if` `(l.second != r.second) {``            ``return` `l.second < r.second;``        ``}``        ``return` `l.first < r.first;``    ``}``};`` ` `// Function to sort the map according``// to value in a (key-value) pairs``void` `sort(map& M)``{`` ` `    ``// Declare set of pairs and insert``    ``// pairs according to the comparator``    ``// function comp()``    ``set, comp> S(M.begin(),``                                   ``M.end());`` ` `    ``// Print the sorted value``    ``for` `(``auto``& it : S) {``        ``cout << it.first << ``' '``             ``<< it.second << endl;``    ``}``}`` ` `// Driver Code``int` `main()``{`` ` `    ``// Declare Map``    ``map M;`` ` `    ``// Given Map``    ``M = { { ``"GfG"``, 3 },``          ``{ ``"To"``, 2 },``          ``{ ``"Welcome"``, 1 } };`` ` `    ``// Function Call``    ``sort(M);``    ``return` `0;``}`
Output:
```Welcome 1
To 2
GfG 3
```

Method 3 – using multimap
Multimap is similar to a map with an addition that multiple elements can have the same keys. Rather than each element is unique, the key-value and mapped value pair have to be unique in this case.
The idea is to insert all pairs from the given map into multimap using originals map’s value as a key in the multimap and original maps key value as a value in the multimap.

Below is the implementation of the above approach:

 `// C++ program for the above approach``#include ``using` `namespace` `std;`` ` `// Function to sort the map according``// to value in a (key-value) pairs``void` `sort(map& M)``{`` ` `    ``// Declare a multimap``    ``multimap<``int``, string> MM;`` ` `    ``// Insert every (key-value) pairs from``    ``// map M to multimap MM as (value-key)``    ``// pairs``    ``for` `(``auto``& it : M) {``        ``MM.insert({ it.second, it.first });``    ``}`` ` `    ``// Print the multimap``    ``for` `(``auto``& it : MM) {``        ``cout << it.second << ``' '``             ``<< it.first << endl;``    ``}``}`` ` `// Driver Code``int` `main()``{`` ` `    ``// Declare Map``    ``map M;`` ` `    ``// Given Map``    ``M = { { ``"GfG"``, 3 },``          ``{ ``"To"``, 2 },``          ``{ ``"Welcome"``, 1 } };`` ` `    ``// Function Call``    ``sort(M);``    ``return` `0;``}`
Output:
```Welcome 1
To 2
GfG 3
```
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up