Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is value in std::unordered_map<std::string, int> initialised by default or not?

I have a following code:

#include <iostream>
#include <unordered_map>
#include <string>

int main()
{
  std::unordered_map<std::string, int> map;
  std::cout << map["foo"]; // -> 0

  return 0;
}

I am using map["foo"] without initialisation.
Is this code valid or UB?

Edit: I tried to compile in godbolt and got 0 output with clang and gcc (trunk version) https://godbolt.org/z/KeWq7nbob.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When operator[] does not find the value with given key one is inserted into the map. From cppreference:

Inserts value_type(key, T()) if the key does not exist. […]

T() is Zero-initialization. For int this bullet applies:

If T is a scalar type, the object is initialized to the value obtained by explicitly converting the integer literal ​0​ (zero) to T.

All is fine in your code. map["foo"] returns a reference to 0 after inserting that 0 together with the key constructed from the string literal "foo" into the map. This is the intended use of std::map::operator[]. If you want to check if an element exists in the map use std::map::find. If you want to find an existing one or insert if none is present, use std::map::insert.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading