Source of back_inserters.cpp


  1: //back_inserters.cpp

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

 11: int main()
 12: {
 13:     cout << "\nThis program illustrates the use of a \"back_inserter\", "
 14:         "which can be used\nif the recipient container supports the "
 15:         "push_back() member function.";
 16:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 18:     cout << "\nFirst we display five integers from a vector:\n";
 19:     vector<int> v;
 20:     for (int i=1; i<=5; i++) v.push_back(i);
 21:     copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
 22:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 24:     cout << "\nThen we copy the five integers from that vector into "
 25:         "an empty deque,\nusing a \"back_inserter\", and then "
 26:         "display the deque to confirm:\n"; 
 27:     deque<int> d;
 28:     copy(v.begin(), v.end(), back_inserter(d));
 29:     copy(d.begin(), d.end(), ostream_iterator<int>(cout, " "));
 30:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 32:     cout << "\nFinally, we copy the same five integers from the vector "
 33:         "into an empty list,\nagain using a \"back_inserter\", and again "
 34:         "displaying the list to confirm:\n"; 
 35:     list<int> lst;
 36:     copy(v.begin(), v.end(), back_inserter(lst));
 37:     copy(lst.begin(), lst.end(), ostream_iterator<int>(cout, " "));
 38:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 39: }