Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't a reverse iterator a formal iterator category according to the C++17 standard?

Tags:

c++

c++17

stl

Reverse iterator is not on the list of iterator category tags, so assumedly it is not a category. So what is it exactly?

like image 333
Nathan Doromal Avatar asked Nov 27 '22 19:11

Nathan Doromal


1 Answers

The iterator categories encode levels of functionality.

  • An input iterator is the bare minimum floor - incrementable and dereferenceable once
  • A forward iterator is an input iterator that you can dereference multiple times and has multipass support.
  • A bidirectional iterator is a forward iterator that you can decrement
  • A random access iterator is a bidirectional iterator that you can O(1) advance by +/- n
  • A contiguous iterator is a random access iterator that refers to contiguous memory

Those levels of functionality are used by algorithms - some algorithms require a certain level of functionality, some algorithms can simply optimize based on certain levels of functionality (e.g. advance(it, n) for random access iterators can just do it += n whereas for forward iterators it has to be ++it in a loop).

But "reversed" isn't a level of functionality - it's just a different way to present the underlying data. A reversed iterator doesn't merit its own iterator category for the same reason a "move" iterator doesn't or a "filtered" iterator doesn't or a "counted" iterator doesn't. Algorithms don't care if the iterators are reversed or not - they work the same way either way. It's not important which way ++it actually moves the iterator.

Reversed iterators are just iterators. std::reverse_iterator is known as an iterator adapter (along with a bunch of others, like std::move_iterator) - it's an iterator that adapts a different iterator. But you could write a reverse iterator that is not an adapter - indeed, you could even write a reverse iterator that isn't bidirectional! These two concepts are orthogonal.

like image 79
Barry Avatar answered Dec 05 '22 10:12

Barry