c++ - 使用 C++ 和 map/unordered_map : the default value for a non-existant key 创建直方图

标签 c++

我正在定义一个小函数来创建整数 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, inserts value_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/

相关文章:

c++ - 为什么是 `std::is_constructible_v<int[2], int, int> == false`

c++ - 如何在不运行 'make install' 的情况下使用 OpenCV?

c++ - GCC 的 <experimental/ranges> 过滤器 View 无法使用无限范围 iota() 进行编译

c++ - 条件语句中的逗号有什么好处?

C++ 演示函数同时使用一个 const 参数,它是一个指针,这是为什么?

c++ - 如何用查找表代替 Sin 函数?

c++ - 配置文件的protobuf

c++ - 将函数原型(prototype)发送到模板如何工作?

c++ - 如何强制执行唯一的错误消息

c++ - 数字的二进制表示的大小