it++; // OK : Widely used expression for moving iterator.
it_prev = it-1; // ERROR : What I expected; + - operators never existed
it_prev = std::prev(it) // OK
it_next3 = it+3; // ERROR : also, nothing like this exists
it_next3 = std::next(it,3) // OK
Why does the Iterator class not have + - operators as member functions?
Or std::prev()
as a member function to do this?
it_prev = it.prev() // nothing like this
Is there a special reason for defining the prev
function external to the iterator?
If prev()
were a member function instead of a free function, it would be less generic since it won't be possible to work with built-in types (e.g., pointers) as iterators:
int *ptr = ...
// ...
ptr.prev() // <-- Pointers don't have member functions!!
whereas with a non-member function template, such as std::prev()
, all is needed for it to work with pointers is a specialization that deals with pointers:
int *ptr = ...
// ...
std::prev(ptr); // <-- OK
Pointers also support the increment and decrement operators (i.e., ++
and --
), so defining them in iterator classes doesn't hinder generic programming. The same reasoning applies to the binary operators +
and -
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With