Answers for "sort map by key c++"

12

how to sort a dictionary by value in python

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))


# Sort by key
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
Posted by: Guest on November-27-2019
2

python sort dictionary by key

In [1]: import collections

In [2]: d = {2:3, 1:89, 4:5, 3:0}

In [3]: od = collections.OrderedDict(sorted(d.items()))

In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
Posted by: Guest on April-03-2020
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

Python Answers by Framework

Browse Popular Code Answers by Language