c++stlstdmappartial-sort

Can I use std::partial_sort to sort a std::map?


There are two arrays, one for ids and one for scores, I want to store the two arrays to a std::map, and use the std::partial_sort to find the five highest scores, then print their ids so, Is there any possible to use the std::partial_sort on std::map?


Solution

  • In std::map, sorting applies only to keys. You can do it using vector:

    //For getting Highest first
    bool comp(const pair<int, int> &a, const pair<int, int> &b){
        return a.second > b.second; 
    }
    int main() {
        typedef map<int, int> Map;
        Map m = {{21, 55}, {11, 44}, {33, 11}, {10, 5}, {12, 5}, {7, 8}};
        vector<pair<int, int>> v{m.begin(), m.end()};
        std::partial_sort(v.begin(), v.begin()+NumOfHighestScorers, v.end(), comp);
        //....
    }
    

    Here is the Demo