Source of vector06.cpp


  1: //vector06.cpp

  3: #include <iostream>
  4: #include <iomanip>
  5: #include <vector>
  6: using namespace std;

  8: int main()
  9: {
 10:     cout << "\nThis program illustrates typical uses of the default "
 11:         "vector class iterator\n(which is a random access iterator), "
 12:         "and also shows the use of operators\n->, [], <, >, <=, >=, "
 13:         "+=, -= and == with vector class iterators. Note the\nstrong "
 14:         "analogies between vector class iterators and pointers.";
 15:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 17:     int a[] = {1, 2, 4, 8, 16, 32, 64};
 18:     vector<int> v(a, a+7); //vector contains array values

 20:     vector<int>::iterator p = v.begin();
 21:     cout << "\nHere are the values in our vector:\n";
 22:     while (p != v.end()) cout << *p++ << " ";  cout << endl;
 23:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 25:     vector<int>::iterator p1 = v.begin(); //point at first component
 26:     vector<int>::iterator p2 = v.end();   //point at one-past-the-last
 27:     cout << "\np1 is set to point at the first component and "
 28:         "p2 to one-past the last.\n";
 29:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 31:     if (p1[2] == p2[-5])
 32:         cout << "\np1[2] == p2[-5] == " << p1[2];
 33:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 35:     cout << "\nNow we perform p1 += 2; and p2 -= 5;.\n";
 36:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 37:     p1 += 2;
 38:     p2 -= 5;
 39:     if (p1 == p2)
 40:         cout << "\np1 == p2, so *p1 == *p2 == " << *p1;
 41:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 43:     p1--;  p2++;
 44:     cout << "\nNow we've performed p1--; and p2++;, so ... ";
 45:     cout << "\np1 < p2  is " << boolalpha << (p1 < p2);
 46:     cout << "\np1 <= p2 is " << boolalpha << (p1 <= p2);
 47:     cout << "\np1 > p2  is " << boolalpha << (p1 > p2);
 48:     cout << "\np1 >= p2 is " << boolalpha << (p1 >= p2);
 49:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 51:     struct Point{int x; int y;};
 52:     Point location1 = {1, 2}, location2 = {4, 5};
 53:     vector<Point> v2;
 54:     v2.push_back(location1);
 55:     v2.push_back(location2);
 56:     vector<Point>::iterator pp = v2.begin();
 57:     cout << "\nLocations (accessed with the -> operator): ";
 58:     cout << "(" << pp->x << ", " << pp->y << ") ";
 59:     ++pp;
 60:     cout << "(" << pp->x << ", " << pp->y << ") ";
 61:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 62: }