【发布时间】:2020-06-22 14:31:45
【问题描述】:
鉴于这张地图:
map<string,pair<mutex,set<string>>> m;
如果键中不存在新元素,我想插入它们。我可以使用operator[] 来做到这一点,即:
string possibly_new_key{"foo"};
m[possibly_new_key];
这将默认构造我的pair<mutex,set>,这也是我想要的。问题是我的程序的性能是我第一个也是最后一个关心的问题。出于这个原因,我想使用map::insert 或map::emplace_hint 并使用提示(无论如何我必须事先计算)来“如果它不存在则插入”。但我无法弄清楚如何正确调用该函数,因为无论我尝试什么,要么
- std::pair 默认构造格式不正确,或者
- std::mutex 不可复制,编译失败。
我想要什么(但没用):
auto it=m.lower_bound(possibly_new_key);
//do_stuff_with_it(it);
auto new_value=make_pair(mutex{},set<string>{});
m.emplace_hint(it, piecewise_construct, forward_as_tuple(possibly_new_key), forward_as_tuple(new_value));
有没有办法使用提示来完成此操作,或者只是默认构造新值或提供默认构造的值并移动它?
【问题讨论】: