¿Cuál es la forma más rápida de insertar/actualizar elementos de mapa std::unordered sin usar un if?
Actualmente tengo un montón de código que se ve así:
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));
}
¿Hay alguna manera de acelerar esto simplemente sobrescribiendo el valor cada vez?
4 answers
Usted acaba de hacer (para map
y unordered_map
)
mydict[key]=value;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-05 12:35:59
Creo que podría ser más rápido así:
auto it = my_dict.find(key);
if( it != my_dict.end() ) {
*it = value;
}
else {
my_dict.insert(std::make_pair(key,value));
}
De esta manera no modificas la estructura del unordered_map
si el key
ya existe y solo tienes una búsqueda.
Otra opción en caso de que no necesite/access value
después:
my_dict[key] = std::move(value);
Esto podría ser mejor en los casos en que la asignación de value
es costosa y se beneficia de la semántica de movimiento.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-05 12:42:16
Para actualizar para C++17, puede usar:
std::unordered_map::insert_or_assign()
Http://en.cppreference.com/w/cpp/container/unordered_map/insert_or_assign
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-18 16:05:31
Por lo general, se evita la escritura adicional mediante la definición de una función que evita que se vuelva a escribir la misma.
Si no tiene acceso a insert_or_assign()
de C++17, puede implementar algo como esto usted mismo:
bool InsertOrAssign(std::unordered_map& m, int key, int value) {
// Your code or one of the suggested answers goes here
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-18 16:20:52