Source of iter_swap1a.cpp


  1: //iter_swap1a.cpp

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

  8: int main()
  9: {
 10:     cout << "\nThis program illustrates the use of the STL iter_swap() "
 11:         "algorithm to swap\ninteger values that are pointed to by two "
 12:         "different iterators that may point\ninto the same vector of "
 13:         "integers, or into two different vectors of integers.";
 14:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 16:     int a1[] = {1, 2, 3, 4, 5};
 17:     vector<int> v1(a1, a1+5);
 18:     cout << "\nHere are the contents of v1:\n";
 19:     for (vector<int>::size_type i=0; i<v1.size(); i++)
 20:         cout << v1.at(i) << " ";
 21:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 23:     int a2[] = {2, 4, 6, 8, 10};
 24:     vector<int> v2(a2, a2+5);
 25:     cout << "\nHere are the contents of v2:\n";
 26:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 27:         cout << v2.at(i) << " ";
 28:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 30:     cout << "\nFirst we swap the end values in v1.";
 31:     iter_swap(v1.begin(), v1.end()-1);
 32:     cout << "\nHere are the contents of the revised v1:\n";
 33:     for (vector<int>::size_type i=0; i<v1.size(); i++)
 34:         cout << v1.at(i) << " ";
 35:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 37:     cout << "\nThen we swap the middle values in v1 and v2.";
 38:     iter_swap(v1.begin()+2, v2.begin()+2);
 39:     cout << "\nHere are the contents of the revised v1:\n";
 40:     for (vector<int>::size_type i=0; i<v1.size(); i++)
 41:         cout << v1.at(i) << " ";
 42:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 43:     cout << "\nHere are the contents of the revised v2:\n";
 44:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 45:         cout << v2.at(i) << " ";
 46:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 47: }