Source of map05.cpp


  1: //map05.cpp

  3: #include <iostream>
  4: #include <map>
  5: #include <utility>
  6: using namespace std;

  8: int main()
  9: {
 10:     cout << "\nThis program illustrates the construction of a map from "
 11:         "an array of pairs.\nThe map is then displayed in two different "
 12:         "ways. The code illustrates the\nuse of a map iterator, the "
 13:         "begin() and end() functions, and the operators\n=, !=, ++, --, "
 14:         "*, -> and == with map iterators.";
 15:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 17:     //Create an array of pairs
 18:     pair<char, int> a[] =
 19:     {
 20:         pair<char, int>('B', 66),
 21:         pair<char, int>('A', 65),
 22:         pair<char, int>('D', 68),
 23:         pair<char, int>('C', 67),
 24:         pair<char, int>('E', 69)
 25:     };
 26:     //Initialize a map with values from the array
 27:     map<char, int> m(a, a+5);

 29:     cout << endl;
 30:     map<char, int>::iterator p;
 31:     for (p = m.begin(); p != m.end(); ++p)
 32:         cout << p->first << " has an ASCII code of " << p->second << ".\n";
 33:     if (p == m.end())
 34:         cout << "Our iterator is now pointing to one-past-the-last position.";
 35:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 37:     p = m.end();
 38:     cout << endl;
 39:     while (p != m.begin())
 40:     {
 41:         --p;
 42:         cout << p->first << " has an ASCII code of " << p->second << ".\n";
 43:     }
 44:     if (p == m.begin())
 45:         cout << "Our iterator is now pointing to the first position.";
 46:     if (*p == *m.begin())
 47:         cout << "\nWe confirm this by checking component equality as well.";
 48:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 49: }