Create A histogram using C++ with map/unordered_map: the default value for a non-existant key

后端 未结 3 2012
盖世英雄少女心
盖世英雄少女心 2021-01-20 17:12

I am defining a small function to create a histogram of a vector of integers, Initially I defined the following function that first test whether the key exists in the map be

相关标签:
3条回答
  • 2021-01-20 17:50

    Yes, the value inserted by [] is guaranteed to be zero. From C++11 23.4.4.3/1:

    Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.

    T() specifies value-initialisation which, for numeric types, means it's initialised with the value zero.

    0 讨论(0)
  • 2021-01-20 17:59

    It is guaranteed to be zero-initialized for built-in types, and default constructed for user-defined types. The guarantee is that if an element for a given key does not exist, one is inserted, with the mapped_type being value initialized. For built-in types such as int, this means zero initialization.

    More information in this reference.

    0 讨论(0)
  • 2021-01-20 18:04

    This is a guarantee by the behavior of std::map's operator [] overload. If the key does not exist then it will be value-initialized for you. Since int, when value-initialized is assigned to zero, you're safe here.

    0 讨论(0)
提交回复
热议问题