Do STL maps initialize primitive types on insert?(STL 映射是否在插入时初始化原始类型?)
问题描述
我有一个像这样的 std::map:
map<wstring,int> Scores;
它存储球员的名字和分数.当有人得分时,我会简单地做:
It stores names of players and scores. When someone gets a score I would simply do:
Scores[wstrPlayerName]++;
当地图中没有键为 wstrPlayerName 的元素时,它会创建一个元素,但它是否在增量之前初始化为零或空值,还是未定义?
When there is no element in the map with the key wstrPlayerName it will create one, but does it initialize to zero or null before the increment or is it left undefined?
每次递增前都要测试元素是否存在吗?
Should I test if the element exists every time before increment?
我只是想知道,因为我认为原始类型的东西在创建时总是未定义的.
I just wondered because I thought primitive-type things are always undefined when created.
如果我写的是:
int i;
i++;
编译器警告我 i 是未定义的,当我运行程序时它通常不为零.
The compiler warns me that i is undefined and when I run the program it is usually not zero.
推荐答案
operator[] 看起来像这样:
operator[] looks like this:
Value& map<Key, Value>::operator[](const Key& key);
如果你用一个尚未在地图中的键调用它,它会默认构造一个值的新实例,把它放在下的地图中>key 你传入,并返回对它的引用.在这种情况下,您有:
If you call it with a key that's not yet in the map, it will default-construct a new instance of Value, put it in the map under key you passed in, and return a reference to it. In this case, you've got:
map<wstring,int> Scores;
Scores[wstrPlayerName]++;
此处的值是 int,并且整数默认构造为 0,就像您使用 int() 初始化它们一样.其他原始类型的初始化方式类似(eg、double()、long()、bool()等.).
Value here is int, and ints are default-constructed as 0, as if you initialized them with int(). Other primitive types are initialized similarly (e.g., double(), long(), bool(), etc.).
最后,您的代码在地图中放置了一个新对 (wstrPlayerName, 0),然后返回对 int 的引用,然后您将其递增.因此,如果您希望事物从 0 开始,则无需测试该元素是否存在.
In the end, your code puts a new pair (wstrPlayerName, 0) in the map, then returns a reference to the int, which you then increment. So, there's no need to test if the element exists yet if you want things to start from 0.
这篇关于STL 映射是否在插入时初始化原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:STL 映射是否在插入时初始化原始类型?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
