Source of map15.cpp


  1: //map15.cpp

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

  8: int main()
  9: {
 10:     cout << "\nThis program illustrates the equal_range() member "
 11:         "function\nof the map interface.";
 12:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 14:     //Create an array of pairs
 15:     pair<char, int> a[] =
 16:     {
 17:         pair<char, int>('D', 68),
 18:         pair<char, int>('E', 69),
 19:         pair<char, int>('F', 70),
 20:         pair<char, int>('G', 71),
 21:         pair<char, int>('H', 72),
 22:         pair<char, int>('I', 73),
 23:         pair<char, int>('J', 74),
 24:         pair<char, int>('K', 75),
 25:         pair<char, int>('L', 76),
 26:         pair<char, int>('M', 77)
 27:     };

 29:     cout << "\nSuppose we begin with a map containing the "
 30:         "following pairs:\n";
 31:     map<char, int> m(a, a+10);
 32:     map<char, int>::iterator p = m.begin();
 33:     while (p != m.end())
 34:     {
 35:         cout << p->first << " " << p->second << endl;
 36:         ++p;
 37:     }
 38:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 40:     cout << "\nWe use the equal_range() function to find the lower "
 41:         "and upper bounds for a key\nin the map, then for a key that "
 42:         "precedes any key in the map, and finally for a\nkey that "
 43:         "follows all keys in the map.";
 44:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 46:     pair<map<char, int>::iterator, map<char, int>::iterator> bounds;

 48:     bounds = m.equal_range('H');
 49:     cout << "\nThe lower bound for the key H is the position of "
 50:         "the pair\n";
 51:     cout << bounds.first->first << " " << bounds.first->second;
 52:     cout << "\nand the upper bound for the key H is the position of "
 53:         "this pair:\n";
 54:     cout << bounds.second->first << " " << bounds.second->second;
 55:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 57:     bounds = m.equal_range('A');
 58:     cout << "\nThe lower bound for the key A is the position of "
 59:         "the pair\n";
 60:     cout << bounds.first->first << " " << bounds.first->second;
 61:     cout << "\nand the upper bound for the key A is the position of "
 62:         "this pair:\n";
 63:     cout << bounds.second->first << " " << bounds.second->second;
 64:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 66:     bounds = m.equal_range('T');
 67:     if (bounds.first == m.end())
 68:         cout << "\nThe lower bound for the key T is the "
 69:             "one-past-the-last position.";
 70:     if (bounds.second == m.end())
 71:         cout << "\nThe upper bound for the key T is the "
 72:             "one-past-the-last position.";
 73:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 74: }