我正在定义一个小函数来创建一个整数向量的直方图.最初,我定义了以下函数,该函数首先在分配或递增值之前测试密钥是否存在于映射中.
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;
}
Run Code Online (Sandbox Code Playgroud)
后来,我发现以下代码也可以在不检查密钥是否存在的情况下工作.因此,不存在的键的默认值应该是ZERO.我想知道这种行为在引用不存在的密钥时保证有一个默认的零值吗?
map<int, int> histogram(vector<int> &a){
map<int, int> hist;
for (auto &x : a){
hist[x]++; // without key existence checking.
}
return hist;
}
Run Code Online (Sandbox Code Playgroud)
是的,插入的值[]保证为零.从C++ 11 23.4.4.3/1:
效果:如果
x地图中没有等效的键,则插入value_type(x, T())到地图中.
T() 指定值初始化,对于数字类型,表示初始化为零值.
| 归档时间: |
|
| 查看次数: |
1328 次 |
| 最近记录: |