Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert or update into an unordered_map without requiring a default constructor

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?

like image 901
Hammerite Avatar asked Dec 07 '18 11:12

Hammerite


People also ask

Can we insert pair in unordered_map?

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.

Does unordered_map maintain insertion order?

No. It's called "unordered" for a reason. If you need to maintain an order of insertion, you've chosen an unsuitable data structure.

How do I add elements to an unordered map?

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.

What happens if we insert duplicate key in unordered_map?

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.


1 Answers

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.

like image 183
Matthieu Brucher Avatar answered Oct 04 '22 20:10

Matthieu Brucher