map::operator[] function

The map::operator[] allows you to access the elements of map container using the subscript ‘[]‘.The map container behaving like an array owes to this function.

1 mapped_type& operator[ ](const key_type& k);
2 mapped_type& operator[ ](key_type&& k); (C++11)

key_type:Type of the first value of the pair element
mapped_type:Type of the second value of the pair element

Link:key_type and mapped_type of pair

Note this function is insecure for accessing the elements of the container.You must prefer the function at().

LinK:map::at function

mapped_type& operator[ ](const key_type& k);

The operator[] accepts a key of the pair element to output the second value of the pair element.So you must know the key to access the value.

k -The key for which the value is to be accessed.

Return type
mapped_type& -The reference to the (second)value of the pair element.

This version is called if the index is a variable.If the index is of literal type then the second overloaded version is called.

Code example

map<int,char> mp{{34 , “Thirty-four”} , {45 , “Fourty-five”} , {89 , “Eighty-nine”} };

int i1=45 , i2=89 , i3=34;

cout<< mp[i1] << endl //calls first version
<< mp[i2] << endl; //calls first version

mp[34]=”ThirtyFour”; ///work fine

cout<< mp[i3] ;


Fourty-five Eighty_nine

If the key supplied is non-existent you will get an undefined value.

int val=50;

cout<< mp[val] ;//undefined


Stop wasting time,earn money($$$) from your website-Join Now!

mapped_type& operator[ ](key_type&& k);(C++11)

This overloaded version is added in C++11.If the index value is a literal then this version is called.Also note using std::move with a variable calls this version.

k – A lvalue to be used for accessing the value.

Return type
mapped_type& A reference to the second value.

Code example

map<string,double>mID {{“String” , 45.423 } , { “@gmail” , 1000 } , { “C++” , 9999 } , { “C++14” , “888” } };

cout<< mID[“@gmail”] << endl
<< mID[“C++14″] << endl;

string st=”C++”;

cout<< mID[std::move(“C++”)] << endl; //calls the second version


cout<< mID[“String”] ;