use*_*112 37 c++ performance unordered-map
我目前有很多代码,如下所示:
std::unordered_map<int,int> my_dict;
.
.
.
// If the key does exist in the dictionary
if(my_dict.count(key) == 1){
my_dict[key] = value;
}
// If its a new key
else{
my_dict.insert(std::make_pair(key,value));
}
Run Code Online (Sandbox Code Playgroud)
有没有什么方法可以通过每次覆盖值来加快速度?
Dan*_*rey 19
我认为这可能是最快的:
auto it = my_dict.find(key);
if( it != my_dict.end() ) {
*it = value;
}
else {
my_dict.insert(std::make_pair(key,value));
}
Run Code Online (Sandbox Code Playgroud)
这样你就不会修改unordered_mapif key已经存在的结构,只有一次查找.
如果您value之后不需要/访问,则另一个选项:
my_dict[key] = std::move(value);
Run Code Online (Sandbox Code Playgroud)
在分配value昂贵且从移动语义中获益的情况下,这可能会更好.
要为C ++ 17更新,可以使用:
std::unordered_map::insert_or_assign()
Run Code Online (Sandbox Code Playgroud)
http://en.cppreference.com/w/cpp/container/unordered_map/insert_or_assign