繁体   English   中英

为什么不能根据其值字段直接使用 std::sort 对 std::map 进行排序

[英]why it isn't possible to sort a std::map directly using std::sort based upon its value field

我已经看到了很多根据值对 std::map 进行排序的解决方案。 但我想知道为什么不能像我写的代码那样直接使用 std::sort 对其进行排序。

#include <iostream>
#include <map>
#include <algorithm>


void print_values(const std::map<size_t, size_t>& map_data) {
    for(const auto& my_pair : map_data)
        std::cout << my_pair.first << " : " << my_pair.second << "\n";
    std::cout << std::endl;
}

bool compare(const std::pair<size_t, size_t>& a, const std::pair<size_t, size_t>& b) {
    return a.second > b.second;
}

int32_t main(int32_t argc, char* argv[]) {
    std::map<size_t, size_t> coins_count;
    coins_count.insert(std::make_pair(1, 2));
    coins_count.insert(std::make_pair(2, 3));
    coins_count.insert(std::make_pair(3, 4));
    coins_count.insert(std::make_pair(4, 2));
    coins_count.insert(std::make_pair(5, 3));
    coins_count.insert(std::make_pair(6, 1));
    coins_count.insert(std::make_pair(7, 2));
    
    print_values(coins_count);
    
    std::sort(coins_count.begin(), coins_count.end(), compare);
    
    print_values(coins_count);

    return EXIT_SUCCESS;
}

std::map被实现为某种按键排序的二叉搜索树。 这意味着std::map必须始终按键排序,使用在构造时为映射定义的比较函数,以便元素查找正常运行。

地图本身总是按键排序。 所以你只能对其他一些可以引用地图元素的东西进行排序。

您可以对一组地图迭代器进行排序:

std::vector<decltype(coins_count)::iterator> vec;
for (auto i = coins_count.begin(), end = coins_count.end(); i != end; ++i) {
    vec.push_back(i);
}
std::sort(vec.begin(), vec.end(),
    [](auto& a, auto& b) { return a->second < b->second; }
);    
for(auto&& i : vec) {
    std::cout << i->first << " : " << i->second << "\n";
}

或者,您可以对一组地图键进行排序:

std::vector<decltype(coins_count)::key_type> vec;
for(auto&& i : coins_count) {
    vec.push_back(i.first);
}
std::sort(vec.begin(), vec.end(),
    [&coins_count](auto& a, auto& b) {
        return coins_count.at(a) < coins_count.at(b);
    }
);
for(auto&& i : vec) {
    std::cout << i << " : " << coins_count.at(i) << "\n";
}

代码将输出:

6 : 1
1 : 2
4 : 2
7 : 2
2 : 3
5 : 3
3 : 4

根据定义,地图的元素始终以排序方式维护。

您可以使用模板参数自己定义此排序,但您不能自己使用std::sort手动更改元素的顺序(即使没有交换任何元素,此调用也会失败)。

暂无
暂无

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

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