Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Point to previous value without decrementing pointer

Tags:

c++

pointers

This is a pretty simple question.

Basically, say I have two iterators, 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?

like image 819
Paradox Avatar asked Apr 23 '26 17:04

Paradox


1 Answers

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;
like image 67
krzaq Avatar answered Apr 25 '26 21:04

krzaq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!