我可以使用 std::partial_sort 对 std::map 进行排序吗?
Can I use std::partial_sort to sort a std::map?
有两个数组,一个是ids,一个是scores,我想把这两个数组存到一个std::map
,然后用std::partial_sort
找出5个最高分,然后打印他们的身份证
那么,是否可以在 std::map
上使用 std::partial_sort
?
没有
您无法重新排列 std::map
中的项目。它似乎总是按升序排列。
在 std::map
中,排序仅适用于键。你可以使用矢量来做到这一点:
//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);
//....
}
这是Demo
有两个数组,一个是ids,一个是scores,我想把这两个数组存到一个std::map
,然后用std::partial_sort
找出5个最高分,然后打印他们的身份证
那么,是否可以在 std::map
上使用 std::partial_sort
?
没有
您无法重新排列 std::map
中的项目。它似乎总是按升序排列。
在 std::map
中,排序仅适用于键。你可以使用矢量来做到这一点:
//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);
//....
}
这是Demo