(This question has the same "question template" as Why does std::max_element require a ForwardIterator? but the answer has to be different, because std::fill
doesn't return an iterator into the output sequence.)
std::fill
is defined to work only when the output range is given by a pair of ForwardIterators. However, the superficially similar std::fill_n
works fine with OutputIterator.
Surely the algorithm is simply
template<class OutIt, class T>
void fill(OutIt first, OutIt last, T value)
{
while (first != last) {
*first = value;
++first;
}
}
What about this algorithm requires ForwardIterator? What am I missing?
Output iterators are not comparable. The ==
and !=
operators are not defined for output iterators.
You need a forward iterator, because it
satisfies the requirements of an input iterator
which supports EqualityComparable.
With output iterators, std::fill
cannot compare first
with last
:
while (first != last) {
Not supported, for output iterators.
std::fill_n
avoids this comparison, it just uses the counter to write to the iterator, so all it needs is an output iterator.