TwenteMaster
TwenteMaster

Reputation: 158

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?

Upvotes: 2

Views: 872

Answers (2)

Saurav Sahu
Saurav Sahu

Reputation: 13944

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

Upvotes: 3

No.

You can't rearrange the items in a std::map. It always appears to be sorted in ascending key order.

Upvotes: 3

Related Questions