| Output insert-iterators and factory functions that create such iterators. | Lecture 5 - slide 21 : 39 Program 1 |
// Demonstration of output iterators and inserters
#include <iostream>
#include <string>
#include <vector>
#include <list>
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);
typedef back_insert_iterator<vector<double> > back_ins_vec_it;
// 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.
back_ins_vec_it 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)
typedef front_insert_iterator<list<double> > front_ins_list_it;
list<double> ld;
for(int i = 1; i <= 10; i++)
ld.push_back(i + i/10.0);
front_ins_list_it 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
typedef insert_iterator<list<double> > ins_list_it;
typename list<double>::iterator ins_begin = ld.begin();
++++++ins_begin; // Advance the iterator 3 positions.
// An inserter that starts inserting at ins_begin
ins_list_it ili = inserter(ld, ins_begin);
*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;
}