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?
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.
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> .
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With