views:

926

answers:

5

Hi

Can anybody tell me how to increment the iterator by 2 times.

iter++ is available - I have to do iter+2 how can I achieve this.

+7  A: 

You could use the 'assignment by addition' operator

iter += 2;
teabot
I was wondering if ++iter++ would work, but I think that would just be confusing.
Xetius
What will happen if the iterator currently points onto the last element? Where will it point after the increment?
sharptooth
@Xetius: You should not do it. It is undefined behavior.
Naveen
++iter++ binds as ++(iter++), iter++ is not a modifiable lvalue so you can't 'do' ++(iter++). If it was allowed, it probably wouldn't do what might be expected of it.
Charles Bailey
+19  A: 
std::advance( iter, 2 );

This method will work for iterators that are not random-access iterators but it can still be specialized by the implementation to be no less efficient than iter += 2 when used with random-access iterators.

Charles Bailey
What will happen if the iterator currently points onto the last element? Where will it point after the increment? I tried with VC++ - it just advances and comparison against vector::end() returns false after that. This is straight way to undefined behaviour, I suppose.
sharptooth
Yes, if you're going to do std::advance with '2', or +=2, or two '++' without checking for 'end' in the middle, then you need some external guarantee that you're not going to go beyond one past the end. (E.g. you might *know* that you're iterating through the even numbered (zero based) items of a collection which is guaranteed to have an even number of items.)
Charles Bailey
+5  A: 

http://www.cplusplus.com/reference/std/iterator/advance/

std::advance(it,n);

where n is 2 in your case.

The beauty of this function is, that If "it" is an random access iterator, the fast

it += n

operation is used (i.e. vector<,,>::iterator). Otherwise its rendered to

for(int i = 0; i < n; i++)
    ++it;

(i.e. list<..>::iterator)

Maik Beckmann
A: 

The very simple answer:

++++iter

The long answer:

You really should get used to writing ++iter instead of iter++. The latter must return (a copy of) the old value, which is different from the new value; this takes time and space.

Note that prefix increment (++iter) takes an lvalue and returns an lvalue, whereas postfix increment (iter++) takes an lvalue and returns an rvalue.

Jonas Kölker
+2  A: 

If you don't know wether you have enough next elements in your container or not, you need to check against the end of your container between each increment. Neither ++ nor std::advance will do it for you.

if( ++iter == collection.end())
  ... // stop

if( ++iter == collection.end())
  ... // stop

You may even roll your own bound-secure advance function.

If you are sure that you will not go past the end, then std::advance( iter, 2 ) is the best solution.

Jem