Home > Mobile >  Why is std::reverse_iterator slower than a direct iterator?
Why is std::reverse_iterator slower than a direct iterator?

Time:05-15

I noticed that std::reverse_iterator always decrements a copy of internal iterator before dereference:

_GLIBCXX17_CONSTEXPR reference
operator*() const
{
    _Iterator __tmp = current;
    return *--__tmp;
}

This is the implementation in GNU standard C library. cppreference.com implements it the same way.

The question: wouldn't it be more efficient to decrement it just one time in reverse iterator constructor instead of decrementing it at every dereference step?

CodePudding user response:

The question: wouldn't it be more efficient to decrement it just one time in reverse iterator constructor instead of decrementing it at every dereference step?

Efficiency is irrelevant when it's not possible to implement reverse iterator that way. Consider a reverse iterator representing rend. In order to get to it, you would have to decrement the internal iterator so that it points before the first element. That's not possible, so the decrement must be delayed until indirection where the impossibility is fine because end iterators are not dereferencible.

  • Related