function template
<iterator>
std::back_inserter
template <class Container>
back_insert_iterator<Container> back_inserter (Container& x);
Construct back insert iterator
Constructs a back-insert iterator that inserts new elements at the end of x.
A back-insert iterator is a special type of output iterator designed to allow algorithms that usually overwrite elements (such as copy) to instead insert new elements automatically at the end of the container.
The type of x needs to have a push_back member function (such as the standard containers vector, deque and list).
Using the assignment operator on the returned iterator (either dereferenced or not), causes the container to expand by one element, which is initialized to the value assigned.
The returned iterator supports all other typical operations of output iterators but have no effect: all values assigned are inserted at the end of the container.
Parameters
- x
- Container on which the iterator will insert new elements.
Container should be a container class with member push_back defined.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// back_inserter example
#include <iostream> // std::cout
#include <iterator> // std::back_inserter
#include <vector> // std::vector
#include <algorithm> // std::copy
int main () {
std::vector<int> foo,bar;
for (int i=1; i<=5; i++)
{ foo.push_back(i); bar.push_back(i*10); }
std::copy (bar.begin(),bar.end(),back_inserter(foo));
std::cout << "foo contains:";
for ( std::vector<int>::iterator it = foo.begin(); it!= foo.end(); ++it )
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
| |
Output:
foo contains: 1 2 3 4 5 10 20 30 40 50
|
Data races
The container (x) is not accessed by the call other than to obtain a reference to it, but the returned object may be used to access or modify it.
Exception safety
Other than if x somehow throws while applying the unary operator& to it, this function never throws exceptions (no-throw guarantee).