Search code examples
c++unordered-map

What does unordered_map returns when looking for a key that doesn't exist


I have an unordered_map<char, mystruct> h.

What does this return if h doesn't contain a key x?

mystruct ms = h['x'];

Solution

  • If the specified key 'x' doesn't exist, std::unordered_map::operator[] will insert a value-initialized mystruct firstly, then return the reference to the inserted mystruct. After that ms is copy-initialized from the inserted mystruct.

    Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

    When the default allocator is used, this results in ... the mapped value being value-initialized.

    Return value
    Reference to the mapped value of the new element if no element with key key existed.