Answers for "sort the map by value in c++"

1

Sort the map by values

Map -- Sort the map by values
Write a method that can sort the Map by values
 
Solution:
public static Map<String, Integer>  sortByValue(Map<String, Integer> map){
List<Entry<String, Integer>> list = new ArrayList(map.entrySet());
list.sort(Entry.comparingByValue());
map = new LinkedHashMap();
for(Entry<String, Integer> each : list) {
map.put(each.getKey(), each.getValue());
}
return map;
}
Posted by: Guest on September-29-2021
0

c++ sort map by value

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
 
typedef std::pair<std::string, int> pair;
 
int main()
{
    // input map
    std::map<std::string, int> map = {
        {"two", 2}, {"one", 1}, {"four", 4}, {"three", 3}
    };
 
    // create an empty vector of pairs
    std::vector<pair> vec;
 
    // copy key-value pairs from the map to the vector
    std::copy(map.begin(),
            map.end(),
            std::back_inserter<std::vector<pair>>(vec));
 
    // sort the vector by increasing the order of its pair's second value
    // if the second value is equal, order by the pair's first value
    std::sort(vec.begin(), vec.end(),
            [](const pair &l, const pair &r)
            {
                if (l.second != r.second) {
                    return l.second < r.second;
                }
 
                return l.first < r.first;
            });
 
    // print the vector
    for (auto const &pair: vec) {
        std::cout << '{' << pair.first << "," << pair.second << '}' << std::endl;
    }
 
    return 0;
}
Posted by: Guest on July-29-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language