¿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?

Author: Jamal, 2013-10-05

4 answers

Usted acaba de hacer (para map y unordered_map)

mydict[key]=value;
 41
Author: Joe,
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.

 15
Author: Daniel Frey,
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

 2
Author: htmlboss,
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
}
 0
Author: Serge Rogatch,
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