由于这是用于记忆,因此这两个选项都不是一个好主意。
对于unique-key容器,emplace
and insert
(除了insert
传入a-value_type
即,pair<const Key, Value>
)可以无条件分配内存并先构造key-value对,如果key已经存在则销毁pair并释放内存;如果您的密钥已经存在,这显然是昂贵的。(他们需要这样做,因为在一般情况下,您必须先构造密钥,然后才能检查它是否存在,并且必须直接在其最终位置构造密钥。)
但是,您还希望避免不必要地复制密钥,因此插入 avalue_type
是不好的 -Key
那里的 const 限定,因此不能从中移动。
最后,您还希望避免额外的查找。不像内存分配那样昂贵,但仍然可以保存它。
因此,我们需要先查找键,并且仅emplace
当键不在地图中时才调用。在 C++11 中,只允许同类查找,因此您必须制作一份args...
.
map<tuple<Args...>, int> cache;
auto key = std::make_tuple(args...);
auto it = cache.lower_bound(key); // *it is the first element whose key is
// not less than 'key'
if(it != cache.end() && it->first == key) {
// key already in the map, do what you have to do
}
else {
// add new entry, using 'it' as hint and moving 'key' into container.
cache.emplace_hint(it, std::move(key), /* value */);
}
在 C++14 中,您可以进行异构查找,这意味着您可以在实际需要时保存副本:
map<tuple<Args...>, int, less<>> cache; // "diamond functor" enables hetergeneous lookup
auto key = std::tie(args...); // this is a tuple<const Args&...> - a tuple of references!
auto it = cache.lower_bound(key); // *it is the first element whose key is
// not less than 'key'
if(it != cache.end() && it->first == key) {
// key already in the map, do what you have to do
}
else {
// add new entry, copying args...
cache.emplace_hint(it, key, /* value */);
}