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?
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.
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.
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.
For built-in types it results in zero-initialization.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With