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