Sorting a Map by value in C++ STL

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Comparator function to sort pairs
// according to second value
bool 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) pairs
void 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 Code
int main()
{
  
    // Declare Map
    map<string, int> M;
  
    // Given Map
    M = { { "GfG", 3 },
          { "To", 2 },
          { "Welcome", 1 } };
  
    // Function Call
    sort(M);
    return 0;
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 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<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 Code
int main()
{
  
    // Declare Map
    map<string, int> M;
  
    // Given Map
    M = { { "GfG", 3 },
          { "To", 2 },
          { "Welcome", 1 } };
  
    // Function Call
    sort(M);
    return 0;
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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) pairs
void 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 Code
int main()
{
  
    // Declare Map
    map<string, int> M;
  
    // Given Map
    M = { { "GfG", 3 },
          { "To", 2 },
          { "Welcome", 1 } };
  
    // Function Call
    sort(M);
    return 0;
}

chevron_right


Output:

Welcome 1
To 2
GfG 3

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.