Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map<int,int> default values

std::map<int,int> mapy; ++mapy[5]; 

Is it safe to assume that mapy[5] will always be 1? I mean, will mapy[5] always get the default value of 0 before '++', even if not explicitly declared, as in my code?

like image 453
Bill Kotsias Avatar asked Apr 19 '10 12:04

Bill Kotsias


People also ask

How do I set a default value on a map?

To initialize the map with a random default value below is the approach: Approach: Declare a structure(say struct node) with a default value. Initialize Map with key mapped to struct node.

Is map ordered by default?

By default, a Map in C++ is sorted in increasing order based on its key.


1 Answers

As soon as you access the map with the [] operator, if the key doesn't exist it gets added. The int gets "value initialization" invoked - so it will get a value of 0.

like image 74
rep_movsd Avatar answered Oct 05 '22 19:10

rep_movsd