Source of copy1a.cpp


  1: //copy1a.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 copy() "
 11:         "algorithm to copy integers\nfrom one vector to another.";
 12:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

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

 21:     //The destination of a copy must be large enough
 22:     //to receive the copied values:
 23:     vector<int> v2(5);
 24:     cout << "\nHere are the contents of v2:\n";
 25:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 26:         cout << v2.at(i) << " ";
 27:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 29:     copy(v1.begin(), v1.end(), v2.begin());
 30:     cout << "\nNow we copy the values from v1 to v2 and re-"
 31:         "display v2.\nHere are the new contents of v2:\n";
 32:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 33:         cout << v2.at(i) << " ";
 34:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 36:     int a[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
 37:     vector<int> v3(a, a+10);
 38:     cout << "\nHere are the contents of v3:\n";
 39:     for (vector<int>::size_type i=0; i<v3.size(); i++)
 40:         cout << v3.at(i) << " ";
 41:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 43:     cout << "\nNow we copy all but the end values from v2 into "
 44:         "v3,\nstarting at position 5 in v3, and then re-display v3.";
 45:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 47:     vector<int>::iterator p;
 48:     p = copy(v2.begin()+1, v2.end()-1, v3.begin()+4);
 49:     cout << "\nHere are the new contents of v3:\n";
 50:     for (vector<int>::size_type i=0; i<v3.size(); i++)
 51:         cout << v3.at(i) << " ";
 52:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 54:     cout << "\nThis time we also recorded the iterator returned by "
 55:         "\nthe copy algorithm and now display the value it points to.";
 56:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 58:     cout << "\nThe value pointed to by this iterator is " << *p << ".";
 59:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 60: }