Top of document
©Copyright 1999 Rogue Wave Software

insert_iterator, inserter


     Insert Iterator

Summary

An insert iterator used to insert items into a collection rather than overwrite the collection.

Contents

Synopsis

#include <iterator>
template <class Container>
class insert_iterator : public output_iterator;

Description

Insert iterators let you insert new elements into a collection rather than copy a new element's value over the value of an existing element. The class insert_iterator is used to insert items into a specified location of a collection. The function inserter creates an instance of an insert_iterator given a particular collection type and iterator. An insert_iterator can be used with vectors, deques, lists, maps and sets.

Interface

template <class Container>
class insert_iterator : public output_iterator {

public:
   insert_iterator (Container&, typename Container::iterator);
   insert_iterator<Container>&
    operator= (const typename Container::value_type&);
   insert_iterator<Container>& operator* ();
   insert_iterator<Container>& operator++ ();
   insert_iterator<Container>& operator++ (int);
};
template <class Container, class Iterator>
insert_iterator<Container> inserter (Container&, Iterator)

Constructor

insert_iterator (Container& x, typename Container::iterator i);

Operators

insert_iterator<Container>&
operator= (const typename Container::value_type& value);
insert_iterator<Container>&
operator* ();
insert_iterator<Container>& 
operator++ ();
insert_iterator<Container>& 
operator++ (int);

Non-member Function

template <class Container, class Iterator>
insert_iterator<Container> 
inserter (Container& x, Iterator i);

Example

 #include <iterator>
 #include <vector>
 #include <iostream.h>
 int main()
 {
   //Initialize a vector using an array
   int arr[4] = {3,4,7,8};
   vector<int> v(arr,arr+4);
   //Output the original vector
   cout << "Start with a vector: " << endl << "     ";
   copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
   //Insert into the middle
   insert_iterator<vector<int> >  ins(v, v.begin()+2);
   *ins = 5;
   *ins = 6;
   //Output the new vector
   cout << endl << endl;
   cout << "Use an insert_iterator: " << endl << "     ";
   copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
   return 0;
 }

Warnings

If your compiler does not support default template parameters, then you need to always supply the Allocator template argument. For instance, you'll have to write:

vector<int, allocator>

instead of:

vector<int>

See Also

back_insert_iterator, front_insert_iterator, Insert Iterators


Top of document