Horje
How Can I Sort a Map by Values in C++?

In C++, maps are associative containers that allow the users to store the data in the form of key-value pairs in some defined order. The maps are sorted in increasing order by default on the basis of the keys. In this article, we will learn how we can sort the Map by its second parameter i.e. values in C++.

Example:

Input:
myMap ={ {10,2}, {20,1}, {30,4}, {40,3}}

Output:
sortedData = { {20,1}, {10,2}, { 40,3}, {30,4}}

Sort a Map by Its Second Parameter in C++

In C++, maps are implemented in red-black trees in which we consider the keys as the parameter for sorting. Due to this implementation, we can not sort the map based on its values. But we can create a vector of pairs and then sort this vector of pairs by its .second value using the std::sort() function.

C++ Program to Sort a Map by its Second Parameter

C++

// C++ program to Sort a Map by Its Second Parameter
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
  
int main()
{
    map<int, int> mp
        = { { 10, 2 }, { 20, 1 }, { 30, 4 }, { 40, 3 } };
  
    // Copy key-value pairs of map  to a vector of pairs
    vector<pair<int, int> > pairs;
  
    for (auto& it : mp) {
        pairs.push_back(it);
    }
  
    cout << "Map before soring:" << endl;
    for (auto& it : mp) {
        cout << it.first << ": " << it.second << endl;
    }
    // Sort the vector based on the second parameter using a
    // lambda function
    sort(pairs.begin(), pairs.end(), [](auto& a, auto& b) {
        return a.second < b.second;
    });
  
    // Print the sorted key-value pairs of map
    cout << "Map after soring:" << endl;
    for (auto& pair : pairs) {
        cout << pair.first << ": " << pair.second << endl;
    }
  
    return 0;
}

Output

Map before soring:
10: 2
20: 1
30: 4
40: 3
Map after soring:
20: 1
10: 2
40: 3
30: 4

Time Complexity: O(N * logN) where N is the total number of elements in the map.
Space Complexity: O(N)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Concatenate Two Vectors in C++? How to Concatenate Two Vectors in C++?
How to Initialize a Deque from a Vector in C++? How to Initialize a Deque from a Vector in C++?
How to Find the Intersection of a Vector and a Set in C++? How to Find the Intersection of a Vector and a Set in C++?
How to Create a shared_ptr in C++? How to Create a shared_ptr in C++?
How to Declare a Static Variable in a Class in C++? How to Declare a Static Variable in a Class in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12