简体   繁体   中英

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

有两个数组,一个用于ID,一个用于分数,我想将两个数组存储到std::map ,并使用std::partial_sort查找五个最高分数,然后打印其ID,因此,是否有可以在std::map上使用std::partial_sort吗?

No.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM