Home > OS >  Increment default constructed int in the unordered map
Increment default constructed int in the unordered map

Time:09-27

I have unordered map of counters, e.g:

std::unordered_map<std::string, std::size_t> counters_;

Do i need to manually create a value before trying to increment it? Will the next line be considered undefined behavior?

std::unordered_map<std::string, std::size_t> counters_;

counters_["non_existing_key"]  = 1;

CodePudding user response:

By using the std::map::operator[], you're creating a new value in the map if it didn't exist before. Furthermore, the value new will be value-initialized, so incrementing the value is well-defined.

  •  Tags:  
  • c
  • Related