The Mystery of reverse_iterator Subtraction in C++ Solved

2025-09-26

The subtraction operator (operator-) is defined for Random Access Iterators (and thus for reverse iterators based on them, like those from std::vector or std::string). It computes the distance between two reverse iterators.

The key point to understand is that it doesn't just calculate the difference of the underlying iterators. Instead, it leverages their relationship

$$\text{distance}(\text{lhs}, \text{rhs}) = \text{rhs}.\text{base}() - \text{lhs}.\text{base}() $$

Wait, notice the order! It's the second reverse iterator's base iterator minus the first reverse iterator's base iterator. This is exactly the opposite of what you'd do with forward iterators (where the distance is lhs - rhs). This reversed subtraction correctly yields the number of elements between lhs and rhs in the reversed sequence.

Let's use a std::vector to see this in action

#include <iostream>
#include <vector>
#include <iterator>

int main() {
    std::vector<int> numbers = {10, 20, 30, 40, 50};

    // rbegin() points to 50
    std::vector<int>::reverse_iterator r_it1 = numbers.rbegin(); 
    
    // rbegin() + 3 steps points to 20
    std::vector<int>::reverse_iterator r_it2 = r_it1 + 3; 

    // The distance in the reversed sequence (50, 40, 30, 20, 10)
    // from 50 (r_it1) to 20 (r_it2) is 3 elements (40, 30, 20).
    // The *difference* between r_it2 and r_it1 is 3.

    // Calculate the distance (r_it2 - r_it1)
    auto distance = r_it2 - r_it1; 

    std::cout << "Element pointed to by r_it1: " << *r_it1 << std::endl; // Output: 50
    std::cout << "Element pointed to by r_it2: " << *r_it2 << std::endl; // Output: 20
    std::cout << "Distance (r_it2 - r_it1): " << distance << std::endl; // Output: 3

    return 0;
}

You cannot directly subtract a std::reverse_iterator from a normal iterator, or vice versa, to get the distance. The types are different.

Trouble

// Assuming 'numbers' is the vector from the previous example
auto it_end = numbers.end();        // Points one past 10 (the "start" of the reverse sequence)
auto r_it_begin = numbers.rbegin(); // Points to 50 (the "start" of the reverse iteration)

// int distance = r_it_begin - it_end; // ERROR! Incompatible types.

Alternative/Solution
Using base() for Comparison

To compare or compute distances across the 'boundary', you need to use the reverse iterator's base() member function, which returns the underlying forward iterator.

The important rule for base() is that r.base() points to the element one position past the element that r currently points to.

// Solution to get the distance of the whole container
// rend().base() is equal to begin()
// rbegin().base() is equal to end() - 1 (points to 10)

// The distance of the whole container:
auto total_distance = numbers.rend().base() - numbers.begin(); // Correct: end() - begin() = 5
std::cout << "Total distance: " << total_distance << std::endl; // Output: 5

// Correct distance calculation using base() for iterators pointing to the same elements:
// r_it2 points to 20 (base is 30)
// r_it1 points to 50 (base is 40)
// The distance between the elements is 3
// Correct distance = r_it1.base() - r_it2.base() -> 40 - 30 = 10 (Wait, this is in indices!)
// To get the number of elements *between* the elements they point to in the original sequence:
// Use std::distance for safety, or careful base() subtraction.

The operator- is a Random Access Iterator operation. If the underlying iterator (like one from std::list or std::map) is only Bidirectional, this operator is not available. Attempting to use it will result in a compile-time error.

Trouble

#include <list>
// std::list::reverse_iterator only supports ++ and --, not arithmetic
std::list<int> my_list = {1, 2, 3};
auto r_it1 = my_list.rbegin();
// auto r_it2 = r_it1 + 1; // ERROR! std::list iterators are not Random Access.
// auto distance = my_list.rend() - my_list.rbegin(); // ERROR!

Alternative/Solution
std::distance

For all iterator categories (including Bidirectional), you can use the std::distance algorithm to safely compute the number of steps

#include <list>
#include <iterator>
#include <iostream>

std::list<int> my_list = {1, 2, 3};
auto r_it_start = my_list.rbegin();
auto r_it_end = my_list.rend();

// std::distance works for Bidirectional and Random Access iterators
auto list_distance = std::distance(r_it_start, r_it_end);

std::cout << "List distance using std::distance: " << list_distance << std::endl; // Output: 3

Note: std::distance is generally safer and more generic. It automatically uses the fast operator- for Random Access Iterators and falls back to a loop for slower iterators like Bidirectional ones.

When you need to find the number of elements between any two reverse iterators, std::distance is the most robust and idiomatic C++ choice, as it works regardless of whether the underlying iterator is Random Access or just Bidirectional.

This approach is highly recommended for generic code

#include <iostream>
#include <vector>
#include <iterator> // Required for std::distance

void print_element_count(auto start_rit, auto end_rit) {
    // std::distance correctly calculates the number of elements
    auto count = std::distance(start_rit, end_rit);
    std::cout << "Elements between iterators: " << count << std::endl;
}

int main() {
    std::vector<int> data = {1, 2, 3, 4, 5, 6, 7};

    // Get reverse iterators
    auto r_it_a = data.rbegin();     // Points to 7
    auto r_it_b = data.rbegin() + 4; // Points to 3 (7 -> 6 -> 5 -> 4 -> 3)

    // Call the generic function
    print_element_count(r_it_a, r_it_b); // Output: 4 (Elements 7, 6, 5, 4 are before 3)

    return 0;
}

cpp



Exploring C++ Timed Mutex: Common Pitfalls and Portable Alternatives

First, what is std::timed_mutex::native_handle? It's a way to access the underlying, platform-specific handle for a timed mutex


Solving Memory Leaks in C++ std::map with unique_ptr and shared_ptr

You might be surprised to learn that there aren't many common troubles directly related to the destructor of std::map itself


Best Practices for std::hash in C++ Concurrent Programming

In C++, std::hash is a special function object that allows you to get a hash value for a given type. Think of a hash value as a unique number that represents a specific object



Mastering C++ File I/O: Understanding and Using std::basic_ofstream::native_handle

In C++, the std::basic_ofstream::native_handle function gives you access to the underlying file handle or file descriptor of a file stream object


C++ Ranges: operator- vs. std::ranges::distance Explained

The operator- for ranges::elements_view::sentinel is designed to calculate the distance between an iterator and a sentinel


C++ std::set::crbegin: Common Problems and Alternative Solutions

In C++, a std::set is an associative container that stores unique elements in a sorted order. The std::set::crbegin member function gives you a constant reverse iterator that points to the last element of the set


Beyond std::bit_xor: Alternative Bitwise XOR Techniques in C++

First off, what is std::bit_xor? It's a function object, which is a class that overloads the function call operator (operator()). It performs a bitwise XOR operation (^) on its two arguments


Layouts in C++23: A Guide to std::layout_left

In C++, std::layout_left is a layout policy for multidimensional arrays, introduced in C++23. It specifies that the elements of a multidimensional array are stored in row-major order


When to Use std::replace vs. std::replace_copy in C++

The most frequent issue people run into is a misunderstanding of what std::replace actually does.Pitfall 1 Expecting it to change the container's size or elements in place


C++ Ranges: chunk_view Operator- Pitfalls & Alternatives

A frequent pitfall when using operator- with ranges::chunk_view::inner_iterator is assuming it behaves like a standard random-access iterator