+-
使用带有map / unordered_map的C创建直方图:不存在的键的默认值
我正在定义一个小的函数来创建整数向量的直方图.最初,我定义了以下函数,该函数首先在分配或递增值之前测试键是否在映射中.

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;
}

后来,我发现以下代码在不检查密钥是否存在的情况下也可以工作.因此,不存在的密钥的默认值应为零.我想知道当引用不存在的键时,此行为是否保证具有默认的零值?

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, inserts value_type(x, T()) into the map.

T()指定值初始化,对于数字类型,这意味着它以零值初始化.

点击查看更多相关文章

转载注明原文:使用带有map / unordered_map的C创建直方图:不存在的键的默认值 - 乐贴网