sort unordered_map by value c++
To sort an unordered_map
by value in C++, you can follow these steps:
- Create a
std::vector
of pairs to store the key-value pairs from theunordered_map
. - Copy the elements from the
unordered_map
to thestd::vector
. - Use the
std::sort
algorithm from the<algorithm>
library to sort thestd::vector
based on the values. - If you want the elements in descending order, you can pass a custom comparator function or use
std::greater
as the third argument in thestd::sort
function. - After sorting, you can create a new
std::unordered_map
and populate it with the sorted elements from thestd::vector
.
Here’s an example code snippet that demonstrates how to sort an unordered_map
by value in C++:
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
bool compare(const std::pair<int, int>& a, const std::pair<int, int>& b) {
return a.second < b.second; // Sort in ascending order based on values
}
int main() {
std::unordered_map<int, int> myMap = {{1, 5}, {2, 3}, {3, 10}, {4, 1}, {5, 7}};
std::vector<std::pair<int, int>> sortedVector(myMap.begin(), myMap.end());
std::sort(sortedVector.begin(), sortedVector.end(), compare);
std::unordered_map<int, int> sortedMap;
for (const auto& pair : sortedVector) {
sortedMap.insert(pair);
}
for (const auto& pair : sortedMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
In this example, we have an unordered_map
called myMap
with integer keys and values. We create a std::vector
called sortedVector
and populate it with the key-value pairs from myMap
.
We then use the std::sort
function to sort the sortedVector
based on the values using the custom comparator function compare
. Finally, we create a new std::unordered_map
called sortedMap
and populate it with the sorted elements from the sortedVector
.
The output of the program will be:
4: 1
2: 3
1: 5
5: 7
3: 10
which is the unordered_map
sorted in ascending order based on values.