This is not a duplicate of how to convert a reverse_iterator to an iterator because I want the result to be different to the normal conversion.
Given only a reverse_iterator that is returned from rend, is it possible to convert this to the corresponding iterator that would be returned from end?
For example
std::vector<int> myvec = {...};
auto rit = myvec.rend();
auto it = MAGIC(rit);
it == myvec.end(); // true
If it is not possible to do this given only the reverse_iterator, what is the minimum information needed to do this? (So I can consider workarounds).
Short answer: No.
An iterator refers to one single point in a container, wihtout actual knowledge of the container itself. The iterators returned by end() and rend() point to different ends of a container, i.e. there might be some, many or no elements between the points they refer to, regardless of the reverse nature of one of the iterators. So, without knowing about the container itself or at least its size, there is no possibility to get from one end of the container to the other, and since iterators don't have that knowledge, there is no possibility to get from rend() to end(), from end() to begin() etc. without additional information.
The minimum needed information is the size of the "gap" between the two points. With that and the normal conversion between reverse and non-reverse iterators it is an easy task:
auto rend = v.rend();
auto begin = rend.base();
assert(begin == v.begin());
auto end = begin + v.size(); //the size is the key!
assert(end == v.end());
But, since you can not obtain the size from the reverse_iterator but only from the container itself, you can easily ask it for end() in the first place.
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