[英]Sort std::unordered_map<std::string, std::atomic<unsigned int>> by values
I've got std::unordered_map<std::string, std::atomic<unsigned int>>
. 我有
std::unordered_map<std::string, std::atomic<unsigned int>>
。
I would like to print the keys and values, sorted by the values. 我想打印键和值,按值排序。
The best solution I've encountered is to create a vector of pairs and sort that 我遇到的最好的解决方案是创建一个向量对并对其进行排序
But as one cannot copy std::atomic<unsigned int>
, what is the most efficient solution? 但是由于无法复制
std::atomic<unsigned int>
,最有效的解决方案是什么?
Making a copy of your data into a vector will work, but you would need to provide a custom operation that calls load()
on your atomic<unsigned>
to make it a plain unsigned
. 将数据的副本复制到向量中是可以的,但是您需要提供一个自定义操作,该操作在您的
atomic<unsigned>
上调用load()
使其成为普通的unsigned
。 Since you are forced to do it anyway, you might as well reverse the order of terms in the pair: 由于无论如何您都被迫这样做,因此不妨反转成对词条的顺序:
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);
}
);
Now that the value is first, the call of std::sort
no longer requires a custom comparator: 现在值是第一个,对
std::sort
的调用不再需要自定义比较器:
std::sort(copy.begin(), copy.end());
Another solution is to copy unordered_map
into multimap
with values being the keys and then print it out: 另一种解决方案是将
unordered_map
复制到以值为键的multimap
,然后将其打印出来:
#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <atomic>
#include <algorithm>
#include <iterator>
int main()
{
std::unordered_map<std::string, std::atomic<unsigned int>> m;
for (auto p : std::initializer_list<std::pair<std::string, unsigned int>>{{ "a", 32},{ "b" , 22 },{ "c" , 32 },{ "d" , 22 },{ "e" , 55 } })
m.emplace(p);
std::multimap<unsigned int, std::string> printmap;
std::transform(m.begin(), m.end(), std::inserter(printmap, printmap.end()),
[](auto const &p) { return std::make_pair(p.second.load(), p.first); });
for (auto const &p : printmap)
std::cout << p.first << " - " << p.second << std::endl;
return 0;
}
Demo: https://ideone.com/MgtMY8 演示: https : //ideone.com/MgtMY8
22 - d
22 - b
32 - c
32 - a
55 - e
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.