Click here to Skip to main content
Click here to Skip to main content

Using the maps

, 23 Jan 2002
Rate this:
Please Sign up or sign in to vote.
The goal of this article is to demonstrate using one of the STL’s associative containers – the map.
Using the maps <!-- Download Links --> <!-- Add the rest of your HTML here -->


The goal of this article is to demonstrate using one of the STL’s associative containers – the map. The associative containers link a key with a value, allowing the value to be found given its key. The most powerful of the associative containers are map and multimap. These allow both the key and value to be of differing and arbitrary data types. The difference between map and multimap is that map requires unique keys and multimap does not.

Therefore, the map class supports an associative container in which unique keys are mapped with values. In essence, a key is simply a name that you give to a value. Once a value has been stored, you can retrieve it by using its key. Thus, in its most general sense a map is a list of key/value pairs. The power of a map is that you can look up a value given its key.

The template specification for map is shown here:

template <class Key, class T, class Comp = less<Key>, 
          class Allocator = allocator<T> class map

Here, Key is the data type of the keys, T is the data type of the values being stored (mapped), and Comp is a function that compares two keys.

The map class contains many useful functions, but I'll put priority on several the most important functions of this class, such as: insert, erase and find, which represents the strongest weapon of this associative container.

These functions are encapsulated inside MyCompanyEmployees class according to business requests.

The test application for this article refers to the system that is responsible for the simple management of employees in a company. This is only prototype, but it's enough to illustrate the power of the map class and its possible usages.

In my test application I use one modified class String Tokenizer too.

As illustration, I’m going to give one relatively simple example with the following class hierarchy:

class Employee
	// Some code

class Employees
  virtual bool InitData() = 0;

  Employee employee;

  virtual bool AddToEmployees( Employee new_employee ) = 0;
  virtual bool RemoveFromEmployees( string ssn ) = 0;
  virtual bool FindEmployee( string ssn, Employee &employee_found ) = 0;

class MyCompanyEmployees : public Employees
  EmployeeMap theMap;
  EmployeeMap::iterator theIterator;

  bool InitData();


  bool AddToEmployees( Employee new_employee );
  bool RemoveFromEmployees( string ssn );
  bool FindEmployee( string ssn, Employee &employee_found );
	STRING_VECTOR GetData( Employee employee );

// MyCompanyEmployees.cpp
#include <span class="code-keyword"><iostream>
#include <span class="code-keyword"><fstream>
#include <span class="code-string">"MyCompanyEmployees.h"
#include <span class="code-string">"StringTokenizer.h"



bool MyCompanyEmployees::AddToEmployees( Employee new_employee )
  bool bRet;
  pair<map<string, Employee>::iterator, bool> result;

  result = theMap.insert( pair<string, Employee>( new_employee.GetSSN(), 
                          Employee( new_employee ) ) );
  if( result.second )
    bRet = true;
    bRet = false;

  return bRet;

bool MyCompanyEmployees::RemoveFromEmployees( string ssn )
  bool bRes;
  int nResult;

  nResult = theMap.erase( ssn );
  if( nResult != 0 )
    bRes = true;
    bRes = false;

  return bRes;

bool MyCompanyEmployees::FindEmployee( string ssn, Employee &employee_found )
  bool bRet;

  theIterator = theMap.find( ssn );
  if( theIterator != theMap.end() )
    employee_found = theIterator->second;
    bRet = true;
    bRet = false;

  return bRet;

bool MyCompanyEmployees::InitData()
  bool bRet = true;
  char row[200];

  ifstream file( "parsing_file.txt", ios::in );
  if( !file )
    cerr << "Error while file opening!";
    bRet = false;
    goto Exit;

  while( !file.eof() )
    file.getline( row, 200 );
    StringTokenizer strtok( row, "," );

    employee.SetSSN( strtok.elementAt( 0 ) );
    employee.SetFirstName( strtok.elementAt( 1 ) );
    employee.SetLastName( strtok.elementAt( 2 ) );
    employee.SetMaritalStatus( strtok.elementAt( 3 ) );
    employee.SetHomeAddress( strtok.elementAt( 4 ) );
    employee.SetHomePhoneNumber( strtok.elementAt( 5 ) );
    employee.SetOfficePhoneNumber( strtok.elementAt( 6 ) );
    employee.SetSalary( strtok.elementAt( 7 ) );
    employee.SetTitle( strtok.elementAt( 8 ) );
    theMap.insert( pair<string, Employee>( employee.GetSSN(), Employee(employee) ) );

  return bRet;

STRING_VECTOR MyCompanyEmployees::GetData( Employee employee )
  vector<string> str_vector;

  str_vector.push_back( employee.GetSSN() );
  str_vector.push_back( employee.GetFirstName() );
  str_vector.push_back( employee.GetLastName() );
  str_vector.push_back( employee.GetMaritalStatus() );
  str_vector.push_back( employee.GetHomeAddress() );
  str_vector.push_back( employee.GetHomePhoneNumber() );
  str_vector.push_back( employee.GetOfficePhoneNumber() );
  str_vector.push_back( employee.GetSalary() );
  str_vector.push_back( employee.GetTitle() );

  return str_vector;

This is pure C++ driver program and main function seems like this:

#include <span class="code-keyword"><iostream>
#include <span class="code-string">"MyCompanyEmployees.h"

typedef vector<string> STRING_VECTOR;

int main( void )
  string ssn;
  Employee emp;
  MyCompanyEmployees MyCompany;
  STRING_VECTOR employee_data;
  STRING_VECTOR::iterator employee_data_iterator;
  char input;

  while( 1 )
    cout << "Enter add(a), remove(r), find(f), quit(q): ";
    cin >> input;

    switch( input )
    case 'a':
        string ssn, first_name, last_name, marital_status, home_address, 
               home_phone_number, office_phone_number, salary, title;
        cout << endl << "Enter SSN: ";
        cin >> ssn;
        cout << "Enter first name: ";
        cin >> first_name;
        cout << "Enter last name: ";
        cin >> last_name;
        cout << "Enter marital status: ";
        cin >> marital_status;
        cout << "Enter home address: ";
        cin >> home_address;
        cout << "Enter home phone number: ";
        cin >> home_phone_number;
        cout << "Enter office phone number: ";
        cin >> office_phone_number;
        cout << "Enter salary: ";
        cin >> salary;
        cout << "Enter title: ";
        cin >> title;
        emp.SetSSN( ssn );
        emp.SetFirstName( first_name );
        emp.SetLastName( last_name );
        emp.SetMaritalStatus( marital_status );
        emp.SetHomeAddress( home_address );
        emp.SetHomePhoneNumber( home_phone_number );
        emp.SetOfficePhoneNumber( office_phone_number );
        emp.SetSalary( salary );
        emp.SetTitle( title );
        if( MyCompany.AddToEmployees( emp ) )
          cout << "Insertion occured...\n";
          cout << "Duplicate not allowed...\n";
    case 'r':
        cout << "Enter SSN that you want to remove: ";
        cin >> ssn;
        if( !MyCompany.RemoveFromEmployees( ssn ) )
          cout << "Error while removing..." << endl;
          cout << "Removing occured..." << endl;
    case 'f':
        cout << "Enter SSN that you want to find: ";
        cin >> ssn;
        if( MyCompany.FindEmployee( ssn, emp ) )
          employee_data = MyCompany.GetData( emp );
          for( employee_data_iterator = employee_data.begin(); 
               employee_data_iterator != employee_data.end(); 
               employee_data_iterator++ )
            cout << *employee_data_iterator;
            if( employee_data_iterator != employee_data.end() - 1 )
              cout << ", ";
          cout << endl;
          cout << "Name not in directory...\n";
    case 'q':
      cout << "Quit\n";
      exit( 0 );
      cout << "Error: Bad command " << input << '\n';

  return 0;

Like a data source you have one simple text (parsing_file.txt) file which is filled with four lines of data:


The first column represents, at the same time, the key in our map, so that if you want to find or remove some data from map you should type only the number: 1111 or 2222 or…

This example could be more useful because we have storing the class object in a map.

I recommend you one very helpful programmer's book that discuss STL topics - "STL programming from ground up", Herbert Schildt.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Tesic Goran
Web Developer
Serbia Serbia
No Biography provided

Comments and Discussions

Questionproblem with erasing map elements Pinmemberpsatyan26-May-06 10:42 
I need help with erasing an element from a map that is in turn a part of a "higher level" map, such that the change is reflected throughout:
if (! m_matchDataList.empty()){
for ( pos = m_matchDataList.begin(); pos != m_matchDataList.end(); ++pos){ //get person
Person *m_p = &pos->second;
int p_no = pos->first;
map<int, Finger> m_finger = m_p->GetFingers();
map<int, Finger>::iterator finger_pos;
for ( finger_pos = m_finger.begin(); finger_pos != m_finger.end(); ++finger_pos) { //get his finger
int f_no = finger_pos->first;
Finger *m_f = m_p->GetSingleFinger(f_no);
map<int, FScan> m_scan = m_f->GetScans();
map<int, FScan>::iterator scan_pos, erase_pos;

for ( scan_pos = m_scan.begin(); scan_pos != m_scan.end(); ) { //look through a list of fingerprint images for each finger
erase_pos = scan_pos;
FScan *m_s = &scan_pos->second;
int s_no = scan_pos->first;
if (m_s->GetTrueAvg() < (m_f->GetTrueAvg()/3)){ //if some condition gets satisfied, erase the image from the entire map
My problem is that if I follow the method above, the member gets deleted from the map m_scan, but this is not reflected in the main map m_matchDataList. I've tried reaching the element to be erased starting from the top level( as in the commented code) but this gives me a debug assert saying that my iterator is out of range.

GeneralC++ Code for Time/Clock Pinmemberamjed2-Mar-02 4:07 
GeneralRe: C++ Code for Time/Clock PinmemberChristian Graus8-Dec-02 23:57 
GeneralGood stuff in STL. PinmemberGiles26-Jan-02 1:32 
GeneralWhy not use CList Pinmembersuger10-Jan-02 21:35 
GeneralRe: Why not use CList PinmemberBill Leibold24-Jan-02 20:01 
GeneralRe: Why not use CList Pinmembermloibl27-Jan-02 22:28 
GeneralRe: Why not use CList PinmemberChristian Graus27-Jan-02 22:38 
GeneralRe: Why not use CList PinmemberSimon Capewell28-Jan-02 0:04 
GeneralRe: Why not use CList PinmemberChristian Graus28-Jan-02 0:18 
GeneralWhy not use CList Pinmembersuger10-Jan-02 21:34 
GeneralNice PinmemberNemanja Trifunovic8-Jan-02 11:00 
GeneralSource code PinmemberMike Klimentiev7-Jan-02 8:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 24 Jan 2002
Article Copyright 2002 by Tesic Goran
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid