class template
std::back_insert_iterator
<iterator>
template <class Container> class back_insert_iterator;
Back insert iterator
Back insert iterators are a special
output iterator class designed to allow
algorithms that usually overwrite elements (such as
copy) to instead insert new elements at the end of the container.
The container must have member
push_back defined (such as standard containers
vector,
deque and
list).
Using the assignment operator on the
back_insert_iterator, even when dereferenced, causes the container to append a new element to it. The other typical operators of an
output iterator are also defined for
back_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
|
template <class Container>
class back_insert_iterator :
public iterator<output_iterator_tag,void,void,void,void>
{
protected:
Container* container;
public:
typedef Container container_type;
explicit back_insert_iterator (Container& x) : container(&x) {}
back_insert_iterator<Container>& operator= (typename Container::const_reference value)
{ container->push_back(value); return *this; }
back_insert_iterator<Container>& operator* ()
{ return *this; }
back_insert_iterator<Container>& operator++ ()
{ return *this; }
back_insert_iterator<Container> operator++ (int)
{ return *this; }
};
|
The library provides a function, called
back_inserter, that automatically generates a
back_insert_iterator class from a container.
Member functions
- constructor
- back_insert_iterator objects are constructed from a 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
|
// back_insert_iterator example
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main () {
vector<int> firstvector, secondvector;
for (int i=1; i<=5; i++)
{ firstvector.push_back(i); secondvector.push_back(i*10); }
back_insert_iterator< vector<int> > back_it (firstvector);
copy (secondvector.begin(),secondvector.end(),back_it);
vector<int>::iterator it;
for ( it = firstvector.begin(); it!= firstvector.end(); ++it )
cout << *it << " ";
cout << endl;
return 0;
}
|
Output:
See also
- back_inserter
- Construct a back insert iterator (function template)
- front_insert_iterator
- Front insert iterator (class template)
- insert_iterator
- Insert iterator (class template)