Looping on C++ iterators starting with second (or nth) item

#include <iterator>

iterator iter = data.begin();
for (advance(iter, 1); iter != data.end(); ++iter)
{
  // do work
}

This relies on >= 1 element in data to avoid an exception, though.


You can use std::next(iter, n) for a linear-time advance. You can also use the standard std::advance algorithm, though it isn't as simple to use (it takes the iterator by a non-const reference and doesn't return it).

For example,

for (mIter = std::next(data.begin()); mIter != data.end(); ++mIter)

or,

mIter = data.begin();
std::advance(mIter, 1);
for (; mIter != data.end(); ++mIter)

Note that you must make sure that data.size() >= 1, otherwise the code will fail in a catastrophic manner.


You could try:

for (mIter = data.begin() ; ++mIter != data.end() ; )

but you'd need to make sure that if data.begin () == data.end () doing the ++mIter doesn't cause a problem.

Since this is a non-standard for loop, using a while loop might be more appropriate as there are fewer preconceived ideas about how they work, i.e. people looking at your code are more likely to read a while statement than a for statement as there is usually a model of how a for loop should work in their head.

mIter = data.begin ();

while (++mIter != data.end ())
{
}