Demonstrate insert_iterator : insert_iterator « STL Algorithms Iterator « C++






Demonstrate insert_iterator

 
 

#include <iostream>
#include <iterator>
#include <vector>
using namespace std;

int main() {
  vector<int> v;
  vector<int>::iterator itr;

  for(int i=0; i<5; i++)
    v.push_back(i);

  cout << "Original array: ";
  itr = v.begin();
  while(itr != v.end())
    cout << *itr++ << " ";
  cout << endl;

  itr = v.begin();
  itr += 2; // point to element 2

  // create insert_iterator to element 2
  insert_iterator<vector<int> > i_itr(v, itr);

  // insert rather than overwrite
  *i_itr++ = 100;
  *i_itr++ = 200;

  cout << "Array after insertion: ";
  itr = v.begin();
  while(itr != v.end())
    cout << *itr++ << " ";

  return 0;
}

/* 
Original array: 0 1 2 3 4
Array after insertion: 0 1 100 200 2 3 4 
 */        
  








Related examples in the same category