我正在定义一个小函数来创建整数 vector 的直方图,最初我定义了以下函数,它首先测试键是否存在于 map 中,然后再分配或增加值。
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;
}
后来,我发现下面的代码在不检查 key 是否存在的情况下也能运行。因此,不存在的键的默认值应该为零。我想知道在引用不存在的键时是否保证此行为具有默认零值?
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:
Effects: If there is no key equivalent to
x
in the map, insertsvalue_type(x, T())
into the map.
T()
指定值初始化,对于数字类型,这意味着它被初始化为零值。
关于c++ - 使用 C++ 和 map/unordered_map : the default value for a non-existant key 创建直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21682716/