iterators/inserters/F14/ins-2.cpp - Same program - simplified in various ways in C++11. | Lecture 6 - slide 6 : 40 Program 2 |
// C++11 version - Still demonstration of output iterators and inserters. // Takes advantages of auto. Uses next instead of chaining of prefix increment. #include <iostream> #include <string> #include <vector> #include <list> #include <iterator> // std::next template <typename CONT> void print_seq(const CONT &v); int main(){ using namespace std; // Make and initialize a vector: vector<double> 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<double> 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 <typename CONT> 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; }