Listing 1: Using an std::map to count words

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

std::map<std::string, int> mapWordCount;

// GetNextWord() is a function that reads the next
// word from the text into its argument and returns
// true while there is more to come.
//
std::string strCurrentWord;
while(GetNextWord(strCurrentWord))
{
  // The following line increments the value for the
  // key strWord in the map, creating an entry with
  // value 1 if this is the first occurrence of the word.
  ++(mapWordCount.insert(std::make_pair(strWord, 0)).first->second);
}

// The following loop prints a list of all words and the number of 
// times each of them occurs:
//
std::map<std::string, int>::const_iterator itCurrent = 
  mapWordCount.begin();
std::map<std::string, int>::const_iterator itEnd = 
  mapWordCount.end();
for(;itCurrent!=itEnd; ++itCurrent)
{
  std::cout << itCurrent->first << " "
            << itCurrent->second << "\n";
}
— End of Listing —