简体   繁体   English

我可以使用std :: partial_sort对std :: map进行排序吗?

[英]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 . 您不能在std::map重新排列项目。 It always appears to be sorted in ascending key order. 它总是看起来是按升序排列的。

In std::map , sorting applies only to keys. std::map ,排序仅适用于键。 You can do it using vector: 您可以使用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 这是演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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