Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the value of primitive types in std::map initialized?

Consider the following code:

map<int,int> m;
for(int i=0;i<10000;++i) m[i]++;
for(int i=0;i<10000;++i) printf("%d",m[i]);

I thought the the values printed out would be undefined because primitive types doesn't have default constructor, but here I got 10000 1s every time I tested.

Why is it initialized?

like image 519
Leo Lai Avatar asked Jul 24 '16 05:07

Leo Lai


People also ask

What is the default value in map in C++?

By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared.

Can we initialize map in C++?

Initialization Using an Array of Pairs The map stores key-value pairs, one can store the key values using the array of pairs of the same type. Syntax: map<string, string>New_map(old_arr, old_arr + n); Here, old_arr is the array of pairs from which contents will be copied into the new_map.

How do you assign a value to a map?

Using insert(): Insert function is used to insert the key-value pair in the map. After insertion, the reordering of elements takes place and the map is sorted w.r.t the key.

Does default constructor zero initialize?

For built-in types it results in zero-initialization.

What is the complexity of std :: map :: insert () method?

Its time complexity is O(logN). insert( ): insert a single element or the range of element in the map. Its time complexity is O(logN), when only element is inserted and O(1) when position is also given.


2 Answers

When invoking operator[] and the key is missing, the value is initialized using the expression mapped_type() which is the default constructor for class types, and zero initialization for integral types.

like image 134
Joseph Garvin Avatar answered Sep 23 '22 02:09

Joseph Garvin


std::map::operator[] inserts new value if it's not exist. If an insertion is performed, mapped value is initialized by default-constructor for class-types or zero-initialized otherwise.

like image 26
Nikita Avatar answered Sep 22 '22 02:09

Nikita