class template
std::insert_iterator
<iterator>
template <class Container> class insert_iterator;
Insert iterator
Insert iterators are special
output iterator class designed to allow
algorithms that usually overwrite elements (such as
copy) to instead insert new elements in the container.
Using the assignment operator on the
insert_iterator, even when dereferenced, causes the container to insert a new element at its beginning. The other typical operators of an
output iterator are also defined for
insert_iterator, but have no effect.
It is defined with an identical operation to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
template <class Container>
class insert_iterator :
public iterator<output_iterator_tag,void,void,void,void>
{
protected:
Container* container;
typename Container::iterator iter;
public:
typedef Container container_type;
explicit insert_iterator (Container& x, typename Container::iterator i)
: container(&x), iter(i) {}
insert_iterator<Container>& operator= (typename Container::const_reference value)
{ iter=container->insert(iter,value); ++iter; return *this; }
insert_iterator<Container>& operator* ()
{ return *this; }
insert_iterator<Container>& operator++ ()
{ return *this; }
insert_iterator<Container> operator++ (int)
{ return *this; }
};
|
The library provides a function, called
inserter, that automatically generates an
insert_iterator class from a container and an iterator.
Member functions
- constructor
- insert_iterator objects are constructed from a container and an iterator pointing to an element of this container.
- operator=
- Inserts a new element in the container, initializing its value to a copy of the argument.
- operator*
- Does nothing. Returns a reference to the object.
- operator++
- Does nothing. Returns a reference to the object.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// insert_iterator example
#include <iostream>
#include <iterator>
#include <list>
using namespace std;
int main () {
list<int> firstlist, secondlist;
for (int i=1; i<=5; i++)
{ firstlist.push_back(i); secondlist.push_back(i*10); }
list<int>::iterator it;
it = firstlist.begin(); advance (it,3);
insert_iterator< list<int> > insert_it (firstlist,it);
copy (secondlist.begin(),secondlist.end(),insert_it);
for ( it = firstlist.begin(); it!= firstlist.end(); ++it )
cout << *it << " ";
cout << endl;
return 0;
}
|
Output:
See also
- inserter
- Construct an insert iterator (function template)
- back_insert_iterator
- Back insert iterator (class template
)
- front_insert_iterator
- Front insert iterator (class template)