Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an iterator operator + return a copy?

Tags:

c++

iterator

If you had an iterator vector<int>::iterator i = vector.begin(), i++ moves the actual iterator down. But why does something like

i = i + 3

give you a new iterator three doors down?

like image 898
dtgee Avatar asked Oct 26 '25 09:10

dtgee


1 Answers

To mimic the natural behaviour that one would expect from +. The same way that in:

int x = 0;
int y = x + 3;

The second line doesn't change x, it just evaluates to the value of 3. However, x++ would modify x.

If you want to advance a generic iterator, you should use std::advance(i, 3) (it will do i += 3 on a Random Access Iterator and i++ three times on any other).

like image 55
Joseph Mansfield Avatar answered Oct 28 '25 21:10

Joseph Mansfield



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!