user2520385 user2520385 - 1 month ago 8
C++ Question

Point to previous value without decrementing pointer

This is a pretty simple question.

Basically, say I have two pointers, it1 and it2. Given a value for it1, I want to define it2 to point to a location one address earlier. It would be cool if I could do it in one line, like:

vector<int>::iterator it2 = --it1;


However, this simultaneously decrements it1, so I have to re-increment it1.

vector<int>::iterator it2 = --it1;
++it1;


If these two lines are involved in a performance-intensive loop, I will have lots of it1 going back and forth for no good reason, just to define it2. On the other hand, if I do:

vector<int>::iterator it2 = it1;
--it2;


This is also slightly less than optimal as it involves two steps. Is there a way to do it in one?

Answer

You're looking for std::prev:

vector<int>::iterator it2 = std::prev(it1);

For vector's iterator, pointers and random access iterator in general, you can also use operator -:

vector<int>::iterator it2 = it - 1;