Source of general_inserters.cpp


  1: //general_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 general "
 14:         "\"inserter\", which can be used\nif the recipient container "
 15:         "supports the insert() member function.";
 16:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 18:     cout << "\nFirst we display the contents of a character vector of "
 19:         "size 6 on one line,\nand the contents of a character list of "
 20:         "size 6 on the next line:\n";
 21:     vector<char> v_c(6, 'A');
 22:     list<char> list_c(6, 'B');
 23:     copy(v_c.begin(), v_c.end(), ostream_iterator<char>(cout));
 24:     cout << endl;
 25:     copy(list_c.begin(), list_c.end(), ostream_iterator<char>(cout));
 26:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 28:     cout << "\nThen we use an \"inserter\" to insert the contents of "
 29:         "the character list into\nthe character vector, beginning at "
 30:         "position 4, and display the contents of\nthe revised vector to "
 31:         "confirm:\n";
 32:     copy(list_c.begin(), list_c.end(), inserter(v_c, v_c.begin()+3));
 33:     copy(v_c.begin(), v_c.end(), ostream_iterator<char>(cout));
 34:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 36:     cout << "\nFinallly, we again use an inserter to insert the contents "
 37:         "of that revised\ncharacter vector back into the character list, "
 38:         "also beginning at position 4,\nand display the contents of the "
 39:         "revised list to confirm:\n";
 40:     list<char>::iterator p=list_c.begin();
 41:     ++p; ++p; ++p;
 42:     copy(v_c.begin(), v_c.end(), inserter(list_c, p));
 43:                                               //__^__
 44:              //Note: Can't use list_c.begin()+3 here. Why not?
 45:     copy(list_c.begin(), list_c.end(), ostream_iterator<char>(cout));
 46:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 47: }