How to increment an iterator by 2?
Solution 1:
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.
Solution 2:
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)
Solution 3:
If you don't have a modifiable lvalue of an iterator, or it is desired to get a copy of a given iterator (leaving the original one unchanged), then C++11 comes with new helper functions - std::next
/ std::prev
:
std::next(iter, 2); // returns a copy of iter incremented by 2
std::next(std::begin(v), 2); // returns a copy of begin(v) incremented by 2
std::prev(iter, 2); // returns a copy of iter decremented by 2
Solution 4:
You could use the 'assignment by addition' operator
iter += 2;