[英]Can I create an unordered_map of string and atomic<int> key-value pairs?
I would like to create an unordered_map
of <string, atomic<int>>
. 我想创建一个
<string, atomic<int>>
的unordered_map
。 I would use this to increment (fetch_add), store or load the values of the atomic based on a string (the key). 我将使用它来增加(fetch_add),基于字符串(键)存储或加载原子的值。 For example, say I have 10 atomic integer counters, but I want to only get the values of 4 or them.
例如,假设我有10个原子整数计数器,但我只想获取4个或它们的值。 I would like a
unordered_map
that looked like this: 我想要一个看起来像这样的
unordered_map
:
unordered_map<string, atomic<int>> myValues = {
{"first", atomic<int>(0)},
{"second", atomic<int>(0)}, ... the last key being "tenth"}
};
Then say I had a vector of strings like 然后说我有一个向量字符串
vector<string> wanted = {"first", "third", "tenth"};
The I would like to do the following: 我想执行以下操作:
for (auto want: wanted) {
cout << myValues[want].load() << endl;
This should print out the values for the keys in wanted. 这应该打印出想要的键的值。
Can I do this? 我可以这样做吗? If I try to create a map as above, I get the error message that the assignment operator for atomic is deleted?
如果尝试如上所述创建地图,则会收到错误消息,即删除了原子的赋值运算符? Is there a way to do this?
有没有办法做到这一点?
Sure, creating an unordered_map<string, atomic<int>>
is possible, but you cannot initialize it using the initializer_list
constructor because atomic<T>
objects are neither moveable nor copyable. 当然,可以创建
unordered_map<string, atomic<int>>
,但是您不能使用initializer_list
构造函数对其进行initializer_list
因为atomic<T>
对象既不可移动也不可复制。
Since the values in your map can be constructed using a single argument, you can use the emplace
member function. 由于可以使用单个参数构造映射中的值,因此可以使用
emplace
成员函数。
std::unordered_map<std::string, std::atomic<int>> m;
for(auto const& key : {"first", "second", "third", "fourth"})
m.emplace(key, 0);
If your key/value type constructor takes more than one argument, to avoid copies and moves, you must use std::pair
's piecewise construction constructor and the emplace
member function. 如果您的键/值类型构造函数使用多个参数,为避免复制和移动,必须使用
std::pair
的分段构造构造函数和emplace
成员函数。
for(auto const& key : {"first", "second", "third", "fourth"})
m.emplace(std::piecewise_construct,
std::forward_as_tuple(key),
std::forward_as_tuple(0));
If your compiler has C++17 support, and the key type can be constructed using a single argument, then you can also use the less verbose try_emplace
member function 如果您的编译器具有C ++ 17支持,并且可以使用单个参数来构造键类型,则还可以使用不太冗长的
try_emplace
成员函数
for(auto const& key : {"fifth", "sixth", "seventh", "eight"})
m.try_emplace(key, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.