Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using a Map

A map is defined as a pair of values: a key, typically a string that serves as an index and a value associated with that key. A dictionary is one example of a map. A program analyzing the occurrence count of words in a text keeps a map with a string key and an integer value representing an occurrence count:

#include <map>
#include <string>
map<string,int> words;

The simplest way to enter a key/value pair is:

words[ "vermeer" ] = 1;

For our word occurrence program, we can write the following:

string tword;
while ( cin >> tword ) 

The expression


retrieves the value associated with the string that tword contains. If tword is not present in the map, it is entered into the map with a default value of 0. The increment operator increments that value by 1.

The following for loop prints the word and its occurrence count:

map<string,int>::iterator it = words.begin();
for ( ; it != words.end(); ++it )
   cout << "key: "  << it->first
      << "value: " << it->second << endl;

The member named first accesses the map's key—in this case, the string representing the word. The member named second accesses the value—in this case, the word's occurrence count.

There are three ways to query a map as to whether a key is present. The obvious way is to apply the key as an index:

int count = 0;
if ( !( count = words[ "vermeer" ] ))
    // vermeer not present

The disadvantage is that indexing a map inserts the key into the map if it is not already present. Its value is given the default value associated with its type. If "vermeer" is not present, for example, this form of search enters it into the map with an occurrence count of 0.

A second way to query the map is to use the find() operation associated with a map (this is not the find() generic algorithm). find() is invoked with the key value:

words.find( "vermeer" );

If the key value is present, find() returns an iterator to the key/value pair. Otherwise, it returns end():

int count = 0;
map<string,int>::iterator it;

it = words.find( "vermeer" );
if ( it != words.end() )
   count = it->second;

A third alternative is to query the map using the count() operation associated with a map. count() returns the number of occurrences of the item within the map:

int count = 0;
string search_word( "vermeer" );

if ( words.count( search_word )) // ok: present ...
   count = words[ search_word ];

A map can have only one occurrence of each key. If we need to store multiple instances of a key, we must use a multimap, which is not discussed in this text.

  • + Share This
  • 🔖 Save To Your Account