C++C++11C++14C++17IteratorsLearn C++

Reverse Iterators in C++

abstract art artistic autumn

By using bidirectional iterator or random access iterator (see Iterator Categories in C++) it’s possible to traverse the sequence in backward direction by using operator -- or by using the special adapter template class std::reverse_iterator. But why to bother with reverse iterators if the operator -- is available for iterators with bidirectional traversing capabilities? The answer is straightforward: because reverse iterators are reusable by the algorithms implemented by using the ordinary iterators such as std::find, for example:

Note that such a re-usability is possible because reverse iterators implements it’s operators “inversely”, for example, consider the following exposition of the possible operator’s ++ implementation:

As described in the Introduction to C++ Iterators the range of sequence is always considered as half-opened: [begin, end), where end serves as the element one-past-the-last element of sequence. However when the sequence is considered in the reverse order one-past-the-last element is
the one-before-the-beginning element of the original sequence. And this imaginary element is inaccessible because it’s not existent in fact. Since the std::reverse_iterator template class adapter is implemented under the hood by using ordinary iterator called current, to get the
half-open range in reverse order without access violation problems, current always points to the element that follows the element referred by reverse iterator, i.e. *reverse == *(current - 1). Therefore, the sequence in reverse order is always considered in range [end - 1, begin - 1), where begin and end corresponds to first and one-past-the-last elements of the original sequence accordingly.

Please note, that it’s always possible to get the underlying current iterator by calling reverse_iterator::base() member function. Finally note, that in order to get the range of sequence of any STL-container in reverse order the standard library provides four functions, demonstrated in the example below:

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.

Related posts
C++C++11C++14C++17C++20Introduction to C++Learn C++

Learn Copy Constructors in C++ Classes

C++C++11C++14C++17Introduction to C++Learn C++Syntax

Learn How To Use Types Of Destructors In C++?

C++C++11C++14Learn C++Syntax

How To Convert u32string To A wstring In C++

C++C++11C++14C++17C++20Introduction to C++Learn C++

How To Learn The Move Constructors In Modern C++?