I have a std::unordered_map
to which I want to add a key-value pair. If the key does not yet exist, then I want it to be added with the given value. If the key already exists, then I want the value to be updated.
The standard advice here, it seems, is to use operator[]
. But this requires the value type of the map to be default-constructible. I wish to avoid providing a default constructor. What should I do?
Unordered Map does not contain a hash function for a pair like it has for int, string, etc, So if we want to hash a pair then we have to explicitly provide it with a hash function that can hash a pair.
No. It's called "unordered" for a reason. If you need to maintain an order of insertion, you've chosen an unsuitable data structure.
std::unordered_map::insert. Inserts new elements in the unordered_map. Each element is inserted only if its key is not equivalent to the key of any other element already in the container (keys in an unordered_map are unique). This effectively increases the container size by the number of elements inserted.
std::unordered_map::count Because unordered_map containers do not allow for duplicate keys, this means that the function actually returns 1 if an element with that key exists in the container, and zero otherwise.
You should use insert_or_assign
(C++17)
As indicated on cppreference you don't need to have default construtible objects in that case:
insert_or_assign returns more information than operator[] and does not require default-constructibility of the mapped type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With