How to erase an element with a reverse iterator from C++ container

The following C++ code demonstrates how to erase an element a reverse iterator points to:

#include <iostream>
#include <set>
#include <cassert>

int main()
{
    std::set<int> set;
 
    set.insert(15);
 
    std::cout << set.size() << " ";
 
    auto ri = set.rbegin();
 
    auto i1 = --ri.base();
 
    auto i2 = --set.end();
 
    assert(i1 == i2);
 
    set.erase(i1);
 
    std::cout << set.size() << std::endl;
}

The output is ‘1 0’. The key point here is that the reverse iterator is an adaptor for reverse-order traversal that can be created from forward iterator with std::make_reverse_iterator.

Leave a Reply

Your email address will not be published. Required fields are marked *