Container Map


In a map you can store the key along with a separate value (of course to make logical sense the key and value should be related). It is a pair associative container. For example: Every employee has an employee ID number as well as a name. The ID will form the key while the value will be the employee name. In a map we call the relationship between the key and the value as one-to-one relationship (i.e. every key has a corresponding single value).

//Program using the 'map' container

#include <iostream>
#include <map>
using namespace std;

int main( )
{
typedef map<int,char,less<int> > mapint;
mapint mapalpha;
mapint::const_iterator ptr;

mapalpha.insert(pair<int,char>(1,'a'));
mapalpha.insert(pair<int,char>(2,'b'));
mapalpha.insert(pair<int,char>(3,'c'));
mapalpha[4]='d';
mapalpha.insert(make_pair(5,'e'));

for (ptr=mapalpha.begin( );ptr!=mapalpha.end( );ptr++)
{
cout<<endl<<ptr->first<<" "<<ptr->second;
}

return 0;
}

The output will be:

1 a
2 b
3 c
4 d
5 e


The code:

typedef map<int,char,less<int> > mapint;

mapint mapalpha;

declares mapalpha to be of type ‘map’ having elements consisting of an integer and a character and arranged in ascending order of the integer (which is the key). Again there are 3 forms of the insert function. We have used the simplest:

mapalpha.insert(pair<int,char>(1,'a'));

This will insert the new pair of values into the container. We are using the class pair to construct the key-value pairs since we need to insert 2 values for each element (the key and the value).

Another way to construct the key-value pair combination is to make use of the make_pair( ) function. This is used in:

mapalpha.insert(make_pair(5,'e'));

Now a pair consisting of an integer value and a character are made and inserted into the map container.

The ‘map’ container also supports the subscript operator which is dual purpose: if the element exists then the value can be updated or else the element can be added.

mapalpha[4]='d';

Since an element with the key of 4 does not exist in the container, the key (4) and value (‘d’) will be added to the container. Suppose the key 4 was existing then the above code would change the value at key 4 into ‘d’. The subscript operator is basically implemented as a form of the insert function.


Go to the next section on: Container MultiMap

Go back to Contents page 2.


Copyright © 2004 Sethu Subramanian All rights reserved.