Reputation: 1272
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?
Upvotes: 4
Views: 179
Reputation: 361302
It is because x + n
should not change the value of x
irrespective of what x
is, whether it is int
or iterator
. The idea is same.
However if you don't want to write this:
it = it + 3;
then you have an alternative, you could write this:
std::advance(it, 3);
Note that in case of some standard containers which do not support random access iterator1, you cannot write it = it + 3
, but you can still write std::advance(it,3)
. For example:
std::list<int>::iterator it = lst.begin();
it = it + 3; //COMPILATION ERROR. `it` is not random access iterator
std::advance(it,3); //okay
So in such cases, std::advance(it,3)
is the only way (or else you've to write such functionality yourself).
1. Note that std::vector<T>::iterator
is random access iterator, that is why you can write it+3
.
Upvotes: 1
Reputation: 103693
When you use operator+
, you don't expect either of the operands to be modified. So that means a new object must be created. Just like if you did this:
int a = 5;
int b = a + 3;
You would still expect a to be equal to 5.
Upvotes: 4
Reputation: 168616
So that you can write:
j = i + 3;
If operator+
didn't create a new copy, what would it do? Modify i
?
Upvotes: 1
Reputation: 110648
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).
Upvotes: 6