Sorting a Map by value in C++ STL - GeeksforGeeks

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 <bits/stdc++.h>using namespace std;  // Comparator function to sort pairs// according to second valuebool cmp(pair<string, int>& a,         pair<string, int>& b){    return a.second < b.second;}  // Function to sort the map according// to value in a (key-value) pairsvoid sort(map<string, int>& M){      // Declare vector of pairs    vector<pair<string, int> > 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 Codeint main(){      // Declare Map    map<string, int> M;      // Given Map    M = { { "GfG", 3 },          { "To", 2 },          { "Welcome", 1 } };      // Function Call    sort(M);    return 0;}
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 <bits/stdc++.h>using namespace std;  // Comparison function for sorting the// set by increasing order of its pair's// second valuestruct 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) pairsvoid sort(map<string, int>& M){      // Declare set of pairs and insert    // pairs according to the comparator    // function comp()    set<pair<string, int>, comp> S(M.begin(),                                   M.end());      // Print the sorted value    for (auto& it : S) {        cout << it.first << ' '             << it.second << endl;    }}  // Driver Codeint main(){      // Declare Map    map<string, int> M;      // Given Map    M = { { "GfG", 3 },          { "To", 2 },          { "Welcome", 1 } };      // Function Call    sort(M);    return 0;}
Welcome 1
To 2
GfG 3

Method 3 – using multimapMultimap 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 <bits/stdc++.h>using namespace std;  // Function to sort the map according// to value in a (key-value) pairsvoid sort(map<string, int>& 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 Codeint main(){      // Declare Map    map<string, int> M;      // Given Map    M = { { "GfG", 3 },          { "To", 2 },          { "Welcome", 1 } };      // Function Call    sort(M);    return 0;}
Welcome 1
To 2
GfG 3

cpp-map
cpp-pair
cpp-vector
C++ Programs
Hash
Sorting
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Program for QuickSort
cin in C++
delete keyword in C++
Shallow Copy and Deep Copy in C++
Passing a function as a parameter in C++
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)