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.

相关文章