The advantage of OutputIterator
is that you can make templates that can take any type of standard container. Another advantage compared to passing an address or a reference is that caller may choose to use to use either std::front_inserter
or std::back_inserter
depending on what order they want and which is faster/possible for their chosen container. The caller may even extend the functionality of the function with the use of a custom iterator.
Here is how you pass an OutputIterator
to an empty container:
template<class Iter>
void foo(Iter it) {}
std::list<int> bar;
foo(std::inserter(bar, bar.begin()));
It's okay to call begin()
on an empty container as long as the returned iterator is not dereferenced.
The reason that begin cannot simply be passed is because begin is not an OutputIterator
.