Hammerite
Hammerite

Reputation: 22350

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?

Upvotes: 7

Views: 1622

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22043

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.

Upvotes: 10

Related Questions