Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::reverse_iterator::base — the underlying iterator

std::reverse_iterator::base returns a copy of the stored underlying iterator. Its position is one element farther in the forward direction than the element accessed through the reverse iterator.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

constexpr Iterator base() const;

std::reverse_iterator::base, declared in <iterator>, returns the stored iterator current by value, with type Iterator. It does not advance the reverse iterator. The result is an iterator, not an element value or a reference to the internal iterator.

For a dereferenceable r, *r behaves like Iterator tmp = r.base(); return *--tmp;. Thus, r.base() is one position farther in the forward direction. To obtain a forward iterator to the same element, copy r.base() and decrement the copy.

At container boundaries, rbegin().base() == end() and rend().base() == begin(). Do not dereference end() or rend(), and do not decrement begin(). Calling base() itself does not dereference the result. In the example, the initial base is past the array; after ++r, the reverse iterator accesses 20, while its base points to 30.

Examples

#include <iostream>
#include <iterator>

int main() {
    int values[] = {10, 20, 30};
    std::reverse_iterator<int*> r(values + 3);

    std::cout << std::boolalpha
              << (r.base() == values + 3) << '\n';
    std::cout << *r << '\n';

    ++r;
    std::cout << *r << ' ' << *r.base() << '\n';

    auto forward = r.base();
    --forward;
    std::cout << *forward << '\n';
}

Result

true
30
20 30
20

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources