使用C ++和map/unordered_map创建直方图:不存在的键的默认值 [英] Create A histogram using C++ with map/unordered_map: the default value for a non-existant key
问题描述
我正在定义一个小的函数来创建整数向量的直方图.最初,我定义了以下函数,该函数首先在分配或递增值之前测试键是否在映射中.
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;
}
推荐答案
是的,保证 []
插入的值为零.从C ++ 11 23.4.4.3/1:
Yes, the value inserted by []
is guaranteed to be zero. From C++11 23.4.4.3/1:
效果:如果地图中没有等效于
x
的键,则将value_type(x,T())
插入地图
Effects: If there is no key equivalent to
x
in the map, insertsvalue_type(x, T())
into the map.
T()
指定值初始化,对于数字类型,这意味着它以零值初始化.
T()
specifies value-initialisation which, for numeric types, means it's initialised with the value zero.
这篇关于使用C ++和map/unordered_map创建直方图:不存在的键的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!