Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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 before assigning or increment the value.

map<int, int> histogram(vector<int> &a){
     map<int, int> hist;
     for (auto &x : a){
         hist[x] = hist.count(x) == 0 ? 1 : hist[x] + 1; // check key existence 
     }
     return hist;
}

Later, I found the following code also works without checking the existence of the key. Therefore the default value for a non-existent key is supposed to be ZERO. I am wondering is this behavior guaranteed to have a default zero value when referencing a key that does not exist?

map<int, int> histogram(vector<int> &a){
     map<int, int> hist;
     for (auto &x : a){
         hist[x]++;        // without key existence checking. 
     }
     return hist;
}
like image 420
SkyOasis Avatar asked Jan 23 '26 22:01

SkyOasis


2 Answers

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.

like image 194
Mike Seymour Avatar answered Jan 25 '26 12:01

Mike Seymour


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.

like image 30
juanchopanza Avatar answered Jan 25 '26 12:01

juanchopanza