C++ 在不使用 if 的情况下插入/更新 std::unordered_map 元素的最快方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19197799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:35:39  来源:igfitidea点击:

What is the quickest way of inserting/updating std::unordered_map elements without using an if?

c++performanceunordered-map

提问by user997112

I currently have lots of code which looks like this:

我目前有很多看起来像这样的代码:

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));
}

Is there any way I can speed this up by just overwriting the value every time?

有什么办法可以通过每次都覆盖该值来加快速度吗?

回答by Joe

You just do (for mapand unordered_map)

你只是做(为mapunordered_map

mydict[key]=value;

回答by Daniel Frey

I think it might be fastest like this:

我认为它可能是最快的:

auto it = my_dict.find(key);
if( it != my_dict.end() ) {
    it->second = value;
}
else {
    my_dict.insert(std::make_pair(key,value));
}

that way you don't modify the structure of the unordered_mapif the keyalready exists and you only have one lookup.

这样,unordered_map如果key已经存在,您就不会修改 的结构,并且您只有一次查找。



Another option in case you don't need/access valueafterwards:

如果您value之后不需要/访问,另一种选择:

my_dict[key] = std::move(value);

This might be better in cases when the assignment of valueis expensive and benefits from move-semantics.

在分配value昂贵且受益于移动语义的情况下,这可能会更好。

回答by htmlboss

To update for C++17, you can use:

要更新 C++17,您可以使用:

std::unordered_map::insert_or_assign()

http://en.cppreference.com/w/cpp/container/unordered_map/insert_or_assign

http://en.cppreference.com/w/cpp/container/unordered_map/insert_or_assign

回答by Serge Rogatch

Usually you avoid extra typing by means of defining a function that saves you from typing the same again. If you don't have access to C++17's insert_or_assign(), you can implement something like this yourself:

通常您通过定义一个函数来避免额外的输入,从而避免再次输入相同的内容。如果您无权访问 C++17's insert_or_assign(),您可以自己实现如下内容:

bool InsertOrAssign(std::unordered_map& m, int key, int value) {
  // Your code or one of the suggested answers goes here
}