STL map container


The STL map container is an associative container.It manages it’s element as a key/value pair.So every single element of a map consists of two parts: key and value .

STL map container

Unlike the sequence container-for instance vector- where the element’s position are determined by the sequence of it’s addition in the container.The map elements however,are sorted in the container by some sorting criteria based on the key of each element.The element’s position is independent of which-is-added-first-comes-first rule.This is one of the main differences between a sequence container and an associative container.

The sorting criteria used by default is ‘less<>‘ ,which compares the elements by using the operator ‘<‘ -sorts elements in ascending order.We can also implement some other criteria instead of using the default criteria. We will discuss more about this in another post(I’ll try to update soon).

In this post we will discuss some of the ways to use map container in our program.The topics which will be discuss here is highlighted below:

i)map initialization
ii)accessing map elements
iii)inserting elements to map
iv)erasing or removing elements from map
v)iterator and map


Initialization

map is a template which has a key/value pair in a single element.This requires that we specify two types when declaring a map object.In other words we must pass two template arguments type during it’s object declaration.A code example is provided below.

map< int , string > mp ;

The first type ‘int’ is a type for the ‘key‘ and the second type string is a type for the ‘value‘.

To initialize the map object we can use list initialization method,for instance for the object ‘mp’ declared above we can initialize it during the declaration as shown below.

map< int , string > mp{ {12 , “New”} , { 8 , “happy” } , { 0 , “Dome”} } ;

/*or*/

map<string ,string > mpSt={ {“Apple” , “New”} , { “ball” , “happy” } };

In the second method the sign ‘=’ is used but both the methods work fine.Also note,the braces( ‘{}’) separates each element.

Another rule that goes without saying is the initializers and the type must match.

map< string , string > mpNew{ { “1223” , “New”} ,
{ “86 number” , “happy” } ,
{ 0 , “Dome”} } ; ///error type does not match

In the third initializer the key is provided as int type which must be a string type,so here you will get an error.

You can also declare an empty object and later you can add elements to it.

map< char , double > mpCD ; ///work fine

Copy constructor and assignment operator

To initialize a map object we can also use another object by calling it’s copy constructor.You may also use the assignment operator ‘=’ to initialize from another object.

map<string ,string > mpCopy(mpSt ) , //copying object
mpAss = mpSt ; //assigning object






accessing map elements

We can either access the elements of the map as a whole-this usually happens when we use a loop statement- or we can also access the key and value of the element singly.Let us discuss accessing the elements wholly first.

Accessing all the elements

Using range-based for loop we can easily access the map elements.You should also prefer this method over other methods because the syntax is way simpler than any other known method.

To get the key value we will call the data member ‘first’ and to get the value we will call the data member ‘second’.Since key comes first and value comes second hence the name ‘first’ and ‘second’ to denote their order.

map< int , string > mp{ {12 , “New”} , { 8 , “happy” } , { 0 , “Dome”} } ;

for(auto elem:mp)
{
cout<< elem.first << ” ” << elem.second << endl;
}

Output

0 Dome
8 happy
12 New

Note the output is sorted in the ascending order of the key magnitude.Automatic sorting of the elements is one of the core features of associative container.

If the key is of string type it will sort the elements in the lexicographical manner of the string.

map<string ,string > mpSt={ {“Apple” , “New”} , { “ball” , “happy” } , {“Aerosmith” , “Hood” } } ;

for(auto elem:mpST )
{
cout<< elem.first << ” ” << elem.second << endl;
}

Ouput

Aerosmith Hood
Apple New
ball happy

duplicate key value is not allowed

Duplicate key is not allowed in map.If the container finds any duplicate key it drop that element.

map<int , double > mpDup{ { 2 , .902 } , { 7 , 3.145 } , { 2 , 999 } };

for(auto elem:mpDup )
{
cout<< elem.first << ” ” << elem.second << endl ;
}

Output

2 .902
7 3.145

The second initializer having the key as 2 is dropped.

Accessing single element

If you know the key of the map you can directly access the element’s value using the subscript ‘[]’ with the key as the index value.

map< int , string > mp{ {12 , “New”} , { 8 , “happy” } , { 0 , “Dome”} } ;

cout<< mp[8] << endl
<< mp[12] ;

Output

happy
New

If the key is a string type then you must use the string as it is to get the value.

map<string ,string > mpSt={ {“Apple” , “New”} , { “ball” , “happy” } } ;

cout<< mpSt[ “Apple” ] << endl
<< mpSt[“ball”] ;

Output

New
happy

Getting the key

It seems there is no way to get the key of the map container elements without using the iterator.Yes,off course we should use the data member ‘first’ to get the key but it requires a pointer or iterator to call it.So this will be discuss later in the section map and iterator.


 


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


inserting elements to map

The simplest way to add element to the container is to call the function ‘insert‘.There are many overloaded version of this function that accepts different types and different number of arguments but,the simplest one accept just one initializer.

map<int , string > mpp ;

mpp.insert( {3, “String” } ) ;

mpp.insert( {2 , “insert” }) ;

for( auto elem : mpp )
{
cout<< elem.first << ” ” << elem.second << endl ;
}

Output

2 insert
3 String

The key is sorted automatically and also if you try to insert the same key twice it is neglected.Consider the example code below.

mpp.insert( {3 , “String again” } );

for(auto elem:mpp)
{
cout<< elem.first << ” ” << elem.second << endl ;
}

Output

2 insert
3 String

The insert call is neglected






erasing or removing elements from map

To remove or erase an element from the map container we can use the member function ‘erase()’ ,this function accept an iterator pointing to the position you want to erase element from.An example is given below.

Note begin() returns an iterator pointing to the first element.

map<int,string>mp={ { 5 , “String” } , { 9 , “New” } , { 0, “erase”} , { 3 , “true”} } ;

mp.erase( mp.begin() ); ///remove the first element

for(auto elem:mp )
{
cout<< elem.first << ” ” << elem.second << endl ;
}

Output

3 true
5 String
9 New



map and iterator

Iterator provide a means to manipulate the map container elements.For instance to access the key of the container we can easily do so using an iterator.

map<string ,string > mpSt={ {“Apple” , “New”} , { “ball” , “happy” } } ;

map<int ,string > ::ietrator mpIt=mpSt.begin( );

cout<< mpIt->first << ” ” << mpIt->second << endl ;

mpIt++ ;

cout << mpIt->first << ” ” << mpIt->second << endl ;

Output

Apple New
ball happy


key is const in map

The key cannot be changed.So it is a const entity.

map<int , string > Map{ {2 ,”String”} , { 9 ,”New”} , { 0 , “Happy”} , { 5 , “Newman”} } ;

map< int , string >::iterator MapIt=Map.begin( ) ;

MapIt->first=4 ; ///error
MapIt->second=”Beginning” ;

If the key is non-constant or changeable it will create discrepancy in the sorted list of the map.Changing it to smaller or larger value will compromise it position in the sorted list.Hence key is const.

 


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