Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment an iterator by 2?

Can anybody tell me how to increment the iterator by 2?

iter++ is available - do I have to do iter+2? How can I achieve this?

like image 622
Cute Avatar asked Jun 29 '09 10:06

Cute


People also ask

How do you decrement an iterator?

The random access iterator can be decremented either by using the decrement operator(- -) or by using arithmetic operation. If itr is an iterator. We can use itr – – or – – itr for decrementing it. As it is a random access iterator we can also use arithmetic operation such as itr=itr-1 for decrementing it.

How do I assign one iterator to another in C++?

In C++11, you say auto it1 = std::next(it, 1); . Prior to that, you have to say something like: std::map<K, T>::iterator it1 = it; std::advance(it1, 1); Don't forget to #include <iterator> .

What happens if you try to move an iterator past the end of a sequence?

Obviously if the iterator is advanced past the last element inside the loop the comparison in the for-loop statement will evaluate to false and the loop will happily continue into undefined behaviour.


2 Answers

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.

like image 73
CB Bailey Avatar answered Sep 30 '22 03:09

CB Bailey


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)

like image 30
Maik Beckmann Avatar answered Sep 30 '22 04:09

Maik Beckmann