c++ - 按值排序 std::unordered_map<std::string, std::atomic<unsigned int>>

标签 c++ c++17

我有 std::unordered_map<std::string, std::atomic<unsigned int>> .

我想打印键和值,按值排序。
我遇到的最好的解决方案是创建一个 vector 对并对其进行排序

但是因为不能复制std::atomic<unsigned int> , 什么是最有效的解决方案?

最佳答案

将数据复制到 vector 中是可行的,但您需要提供调用 load() 的自定义操作在你的 atomic<unsigned>让它成为一个普通的 unsigned .由于无论如何你都被迫这样做,你不妨颠倒这对中术语的顺序:

std::vector<pair<unsigned int,std::string>> copy;
std::transform(
    m.begin()
,   m.end()
,   back_inserter(copy)
,   [](const pair<const std::string, std::atomic<unsigned int>>& p) {
        return make_pair(p.second.load(), p.first);
    }
);

既然值在前,调用std::sort不再需要自定义比较器:

std::sort(copy.begin(), copy.end());

Demo.

关于c++ - 按值排序 std::unordered_map<std::string, std::atomic<unsigned int>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50774478/

相关文章:

c++ - 你能帮我清除这个错误吗

java - jFieldId int 对对象无效

c++ - 为什么我不能推导出类模板参数之一?

c++ - 在 C++11(或更新版本)中创建 RAII 包装器而无需编写新类的最短路径是什么?

c++ - 在 C++17 中的每个实例化中生成一个新类型

c++ - 如何将浮点算法转换为定点算法?

c++ - 在 Windows 7 中管理应用程序音量

c++ - 在 Windows 中将 libmysql.lib 与 gcc 或 dev c++ 链接起来

c++ - constexpr 算法 all_of 编译器错误

c++ - 如何在 Qt Creator 的 constexpr 函数中使用循环?