做STL映射初始化基本类型插入? [英] Do STL maps initialize primitive types on insert?

查看:99
本文介绍了做STL映射初始化基本类型插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 std :: map 像这样:

  map< wstring,int>分数; 

它存储玩家和分数的名称。当有人获得分数时,我只需:

  Scores [wstrPlayerName] ++; 

当地图中没有使用键 wstrPlayerName 它会创建一个,但是它在增量之前初始化为零或null,或者是未定义的?



我应该测试每一次元素是否存在

$ p
b <$ p

$

$ <$>

$ p> 价值& map< Key,Value> :: operator [](const Key& key);

如果您使用它将默认构造 Value 的新实例,将其放在您传入的下的地图中,并返回对它的引用。在这种情况下,您有:

  map< wstring,int>分数; 
Scores [wstrPlayerName] ++;

这里的值是 int ,ints默认构造为0,好像您使用 int()初始化它们。其他基本类型类似地初始化(例如, double() long() bool() 。)。最后,你的代码在映射中放入一个新的对(wstrPlayerName,0),然后返回对int的引用,然后你会增加。所以,没有必要测试元素是否存在,如果你想要的事情从0开始。


I have a std::map like this:

map<wstring,int> Scores;

It stores names of players and scores. When someone gets a score I would simply do:

Scores[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?

解决方案

operator[] looks like this:

Value& map<Key, Value>::operator[](const 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]++;

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.).

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映射初始化基本类型插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆