Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

c++ - Do STL maps initialize primitive types on insert?

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?

I just wondered because I thought primitive-type things are always undefined when created.

If I write something like:

int i;
i++;

The compiler warns me that i is undefined and when I run the program it is usually not zero.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...