Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use the prefix increment form for iterators? [duplicate]

Tags:

c++

iterator

Johannes Schaub claims here

always use the prefix increment form for iterators whose definitions you don't know. That will ensure your code runs as generic as possible.

for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
    /* std::cout << *it; ... */
}

Why doesn't this first iterate it, then start the loop (at v.begin() + 1)?

like image 629
jacknad Avatar asked Jan 20 '17 14:01

jacknad


1 Answers

Why doesn't this first iterate it, then start the loop (at v.begin() + 1)?

The iteration statement is always executed at the end of each iteration. That is regardless of the type of increment operator you use, or whether you use an increment operator at all.

The result of the iteration statement expression is not used, so it has no effect on how the loop behaves. The statement:

++it;

Is functionally equivalent to the statement:

it++;

Postfix and prefix increment expressions have different behaviour only when the result of the expression is used.


Why use the prefix increment form for iterators?

Because the postfix operation implies a copy. Copying an iterator is generally at least as slow, but potentially slower than not copying an iterator.

A typical implementation of postfix increment:

iterator tmp(*this); // copy
++(*this);           // prefix increment
return tmp;          // return copy of the temporary
                     // (this copy can be elided by NRVO)

When the result is not used, even the first copy can be optimized away but only if the operation is expanded inline. But that is not guaranteed.


I wouldn't blindly use the rule "always use prefix increment with itrators". Some algorithms are clearer to express with postfix, although that is just my opinion. An example of an algorithm suitable for postfix increment:

template<class InIter, class OutIter>
OutIter copy(InIter first, InIter last, OutIter out) {
    while(first != last)
        *out++ = *first++;
    return out;
}
like image 200
eerorika Avatar answered Oct 26 '22 02:10

eerorika