C++ · Data Structure

STL – Map

In fact, the STL’s map class allows you to store data by any type of key instead of simply by a numerical key, the way you must access an array or vector. So instead of having to compute a hash function and then access an array, you can just let the map class do it for you.

To use the map class, you will need to include <map> and maps are part of the std namespace. Maps require two, and possibly three, types for the template:

std::map <key_type, data_type, [comparison_function]>

Here’s how you could declare a variable called grade_list that associates strings (student names) with characters (grades — no + or – allowed!).

std::map <string, char> grade_list;

Now, to actually store or access data in the map, all you need to do is treat it like a normal array and use brackets. The only difference is that you no longer use integers for the index — you use whatever data type was used for the key.

For instance, following the previous example, if we wanted to assign a grade of ‘B’ to a student named “John”, we could do the following:

grade_list["John"] = 'B';

If we later decided that John’s grades had improved, we could change his grade in the same fashion:

grade_list["John"] = 'B';
// John's grade improves
grade_list["John"] = 'A';

For instance, to erase “John” from our map, we could do the following:


For instance, to find the size of our hypothetical class, we could call the size function on the grade list:

std::cout<<"The class is size "<<grade_list.size()<<std::endl;

If you want guarantee that the map is empty, you can use the clear function. For instance:


For instance, the following sample shows the use of an iterator (pointing to the beginning of a map) to access the key and value.

std::map <string, char> grade_list;
grade_list["John"] = 'A';
// Should be John
// Should be A

sample code

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main()
map<int, string> students;
students[1] = “Ahmed”;
students[2] = “Yehia”;
students[3] = “Ibrahim”;
students[4] = “Omar”;
students[5] = “Mohamed”;

cout << students.size() << endl;
students.insert(pair<int,string>( 6, “Ali”));

/*map<int, string>::iterator it = students.find(3);

cout << “Key found with value: ” << it->second << endl;*/

map<int, string>::iterator it = students.find(4);
for (map<int, string>::iterator it = students.begin(); it != students.end(); it++){
cout << it->first << ” => ” << it->second << endl;

return 0;



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s