Search code examples
c++reverse-iterator

How to increase/decrease reverse_iterator by any value using difference_type


I'm trying to erase a particular item of a list from the reverse position using reverse_iterator.But an compilation error occurred in stl_iterator.h header file.

I'm trying to do...

here input[] is an integer array.

 list<int>:: reverse_iterator it = l.rbegin()+ input[j];
                    l.erase( std::next(it).base() );

error showing at stl_iterator.h file...

 reverse_iterator
      operator+(difference_type __n) const
      { return reverse_iterator(current - __n); }

I need to erase an particular item starting from back/end of that list.This is only for optimization or to reduce time complexity.


Solution

  • Only random access iterators support operator+. A list iterator is not random access iterator. To advance a non-random access iterator, you can use std::advance or std::next. Like so:

    std::next(l.rbegin(), input[j])