// C++11 version - Still demonstration of output iterators and inserters. // Takes advantages of auto. Uses next instead of chaining of prefix increment. #include #include #include #include #include // std::next template void print_seq(const CONT &v); int main(){ using namespace std; // Make and initialize a vector: vector vd; for(int i = 1; i <= 10; i++) vd.push_back(i + i/10.0); // BACK INSERT ITERATOR: // Make back insert iterator (an output iterator). // The back inserter overloads the assignment operator, // see The C++ Programming Language 3ed, page 556. auto bii = back_inserter(vd); *bii = 20; *bii = 21; print_seq(vd); // 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 11 20 21 // FRONT INSERT ITERATOR (cannot be used on vector) list ld; for(int i = 1; i <= 10; i++) ld.push_back(i + i/10.0); auto fii = front_inserter(ld); *fii = -3; *fii = -5.7; 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 // INSERT ITERATOR (on the list ld. Will also work on the vector vd). auto ins_begin = ld.begin(); auto pos = next(ld.begin(), 3); // Advance the iterator 3 positions. // An inserter that starts inserting at ins_begin auto ili = inserter(ld, pos); *ili = 100; *ili = 101; 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 } // Print the sequence v on standard output: template void print_seq(const CONT &v){ typename CONT::const_iterator it = v.begin(); while(it != v.end()){ std::cout << *it << " "; it++; } std::cout << std::endl; }