Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::fill use ForwardIterator, not OutputIterator?

Tags:

c++

iterator

stl

(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?

like image 560
Quuxplusone Avatar asked Dec 24 '22 18:12

Quuxplusone


1 Answers

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.

like image 136
Sam Varshavchik Avatar answered Jan 06 '23 14:01

Sam Varshavchik