How to sort a map by value
To sort a map by value in cpp we first convert the map to a vector of pairs and then define a comparator function with the desired sort order. Then we sort the vector using the comparator function.
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
bool comp(const std::pair<std::string, int>& left,
const std::pair<std::string, int>& right) {
return left.second < right.second; // sort ascending
}
int main() {
std::map<std::string, int> my_map{{"world", 2}, {"!", 3}, {"hello", 1}};
std::vector<std::pair<std::string, int>> temp_vec(my_map.begin(), my_map.end());
std::sort(temp_vec.begin(), temp_vec.end(), comp);
// in c++20 we can use the following without a comparator function
// std::ranges::sort(temp_vec, {}, &std::pair<std::string, int>::second); // sort ascending
std::cout << temp_vec[0].first << " " << temp_vec[1].first << temp_vec[2].first;
}
// prints "hello world!"