We recommend using Visual Studio 2017
This documentation is archived and is not being maintained.

map::insert, map::find, and map::end

Illustrates how to use the map::insert, map::find, and map::end Standard Template Library (STL) functions in Visual C++.

iterator map::end( ); 
iterator map::find(
   const Key& Key
pair<iterator, bool> 
   const value_type& x


The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.

The end function returns an iterator that points one past the end of a sequence. find returns an iterator that designates the first element whose sort key equals Key. If no such element exists, the iterator equals end. If the key does not already exist, insert will add it to the sequence and return pair<iterator, true>. If the key already exists, insert does not add it to the sequence and returns pair <iterator, false>. The following sample creates a map of ints to strings. In this case, the mapping is from digits to their string equivalents (1 -> "One", 2 -> "Two", and so on). The program reads a number from the user, finds the word equivalent for each digit (using the map), and prints the number back as a series of words. For example, if the user enters 25463, the program responds with: Two Five Four Six Three.

// map_insert_find_end.cpp
// compile with: /EHsc
#pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <map>

using namespace std;

typedef map<int, string, less<int> > INT2STRING;

int main()
   // 1. Create a map of ints to strings
   INT2STRING theMap;
   INT2STRING::iterator theIterator;
   string theString = "";
   unsigned int index;

   // Fill it with the digits 0 - 9, each mapped to its string counterpart
   // Note: value_type is a pair for maps...

   // Read a Number from the user and print it back as words
   for( ; ; )
      cout << "Enter \"q\" to quit, or enter a Number: ";
      cin >> theString;
      if (theString == "q")

      // extract each digit from the string, find its corresponding
      // entry in the map (the word equivalent) and print it
      for (index = 0; index < theString.length(); index++)
         theIterator = theMap.find(theString[index] - '0');
         if (theIterator != theMap.end() )   // is 0 - 9
            cout << (*theIterator).second << " ";
         else    // some character other than 0 - 9
            cout << "[err] ";
      cout << endl;


Enter "q" to quit, or enter a Number: 12
One Two
Enter "q" to quit, or enter a Number: q

Header: <map>