Why does std :: fill use ForwardIterator and not OutputIterator?
(This question has the same "question pattern" as Why does std :: max_element require a ForwardIterator? But the answer must be different because it std::fill
does not return an iterator in the output sequence.)
std::fill
defined only for operation when the output range is specified by a pair of ForwardIterators. However, a superficially similar std::fill_n
works fine with the OutputIterator.
Of course the algorithm is just
template<class OutIt, class T>
void fill(OutIt first, OutIt last, T value)
{
while (first != last) {
*first = value;
++first;
}
}
How about this algorithm requires a ForwardIterator? What am I missing?
source to share
Output iterators are not comparable. Operators ==
and are !=
not defined for output iterators.
You need a forward iterator because it
satisfies the requirements of the input iterator
which supports EqualityComparable.
With output iterators std::fill
can not be compared first
with last
:
while (first != last) {
Not supported for output iterators.
std::fill_n
avoids this comparison, it just uses a counter to write to the iterator, so all it needs is an output iterator.
source to share
There is no concept of "range" for OutputIterator
. Thus, you must provide a repeat count. With the help ForwardIterator
you can work with several elements.
These are semantically different things. fill_n
is intended to add some elements starting from the supplied iterator. fill
is designed to change the range of elements.
Take insert (like a back_inserter
) for example. You can insert more elements than the container, so last
it doesn't even make sense.
OutputIterator
gives you a place where you can throw the object. ForwardIterator
objects must exist.
From cppreference :
The only valid use of the * operator with an output iterator is to the left of the assignment: the * operator can return a proxy object that defines the member operator = (which can be a pattern)
This means that you basically cannot read from it, which is in contrast to ForwardIterator
:
A ForwardIterator is an Iterator that can read data from the specified element.
source to share