00 /*
01  * inserters.cpp
02  *
03  *      Author: Simonas Saltenis / Kurt Nørmark
04  */
05 
06 
07 #include <iostream>
08 #include <string>
09 #include <vector>
10 #include <list>
11 #include <iterator>   // std::next
12 
13 template <typename CONT> void print_seq(const CONT &v);
14 
15 int main()
16 {
17   using namespace std;
18 
19   // Make and initialize a vector:
20   vector<double> vd;
21   for(int i = 1; i <= 10; i++)
22      vd.push_back(i + i/10.0);
23 
24   // BACK INSERT ITERATOR:
25   // Make back insert iterator (an output iterator).
26   // The back inserter overloads the assignment operator,
27   auto bii = back_inserter(vd);
28 
29   *bii = 20;
30   *bii = 21;
31 
32   print_seq(vd);  // 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 11 20 21
33 
34 
35   // FRONT INSERT ITERATOR
36   // Cannot be used on vector: container has to have a push_front operation
37 
38   list<double> ld;
39   for(int i = 1; i <= 10; i++)
40      ld.push_back(i + i/10.0);
41 
42   auto fii = front_inserter(ld);
43   *fii = -3;
44   *fii = -5.7;
45 
46   print_seq(ld);   // -5.7 -3 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 11
47 
48   // INSERT ITERATOR   (on the list ld. Will also work on the vector vd).
49   auto ins_begin = ld.begin();
50   auto pos = next(ld.begin(), 3);    // Advance the iterator 3 positions.
51 
52   // An inserter that starts inserting at ins_begin
53   auto ili = inserter(ld, pos);
54 
55   *ili = 100;
56   *ili = 101;
57   print_seq(ld);   // -5.7 -3 1.1 100 101 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 11
58 
59 }
60 
61 // Print the sequence v on standard output:
62 template <typename CONT> void print_seq(const CONT &v){
63   typename CONT::const_iterator it = v.begin();
64   while(it != v.end()){
65      std::cout << *it << " ";
66      it++;
67   }
68   std::cout << std::endl;
69 }
70 
71 
72