[英]Cannot access key-value pair in a C++ unordered_map from a detached thread
[英]C++ Updating values in a unordered_map, where the data type of key-value pair is int-unordered_set
我正在解决一个 DSA 问题并在 C++ 标准模板库中观察到一个稍微奇怪的行为:
vector<int> v = {1, 7, 8, 3, 12};
unordered_map<int, unordered_set<int>> ump;
for (int i=0; i<v.size(); i++) {
unordered_set<int> us;
us.insert(56);
ump.insert(mp(v[i], us));
}
for (int i=0; i<v.size(); i++) {
unordered_set<int> us = ump.find(v[i])->second;
us.insert(67);
}
for (auto it = ump.begin(); it != ump.end(); it++) {
cout << it->first << ": ";
for (auto ait = it->second.begin(); ait!=it->second.end(); ait++) {
cout << *ait << ' ';
}
cout << '\n';
}
这里的 output 将成为:
12: 56
3: 56
8: 56
7: 56
1: 56
但预期的 output 应该是:
12: 67 56
3: 67 56
8: 67 56
7: 67 56
1: 67 56
我想问题是在将值插入集合的过程中出现的。 而且我还认为,问题在某种程度上与“通过参考改变价值观”有关。 但不确定是什么原因造成的。 我做了更多实验,发现下面的代码片段有效。 但是还是不确定,上面的代码哪里出了问题?
在下面的代码片段中,我没有通过引用直接更新集合,而是复制了一份。 然后插入我的值并再次将其复制到 map 中,它起作用了。
vector<int> v = {1, 7, 8, 3, 12};
unordered_map<int, unordered_set<int>> ump;
for (int i=0; i<v.size(); i++) {
unordered_set<int> us;
us.insert(56);
ump.insert(mp(v[i], us));
}
for (int i=0; i<v.size(); i++) {
unordered_set<int> us = ump.find(v[i])->second;
unordered_set<int> us1;
for (auto it = us.begin(); it!=us.end(); it++) {
us1.insert(*it);
}
us1.insert(67);
ump.find(v[i])->second = us1;
}
for (auto it = ump.begin(); it != ump.end(); it++) {
cout << it->first << ": ";
for (auto ait = it->second.begin(); ait!=it->second.end(); ait++) {
cout << *ait << ' ';
}
cout << '\n';
}
这里的 output 正好等于预期的值:
12: 67 56
3: 67 56
8: 67 56
7: 67 56
1: 67 56
unordered_set<int> us = ump.find(v[i])->second;
制作该集合的副本,以便您的修改不会更改ump
中的值。 您需要改用参考:
unordered_set<int>& us = ump.find(v[i])->second;
或者使用auto
:
auto& us = ump.find(v[i])->second;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.