Source of distance.cpp


  1: //distance.cpp

  3: #include <iostream>
  4: #include <list>
  5: #include <iterator>
  6: #include <algorithm>
  7: using namespace std;

  9: int main()
 10: {
 11:     cout << "\nThis program illustrates the use of the distance() "
 12:         "function\nto compute the number of positions between two "
 13:         "iterators.";
 14:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 16:     int a[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
 17:     list<int> intList(a, a+10);
 18:     cout << "\nHere are the values in a list of integers:\n";
 19:     copy(intList.begin(), intList.end(), ostream_iterator<int>(cout, " "));
 20:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 22:     list<int>::iterator p1 = intList.begin();
 23:     list<int>::iterator p2 = intList.end();
 24:     ++p1; ++p1; ++p1; //p1 now points at 4th value
 25:     --p2; --p2;       //p2 now points at 2nd-last value (8th value)
 26:     cout << "\np1 is pointing at the value " << *p1 << " (the 4th value).";
 27:     cout << "\np2 is pointing at the value " << *p2 << " (the 9th value).";
 28:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 30:     cout << "\nThe number of values (or positions) \"between\" "
 31:         "these two values\n(inclusive) is "
 32:         << (int)distance(p1, p2) + 1 << " (= 9-4+1).";
 33:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 34: }