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

user511493 picture user511493 · Nov 18, 2010 · Viewed 14.7k times · Source

I am looking for a readable, elegant way to do the following in C++, here shown in Python:

for datum in data[1:]:
    do work.

The iterators on the data in question may not support random access iterators, so I can't just use:

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

The best I've come up with is the following:

iterable::iterator mIter = data.begin();
for (mIter++;  mIter != allMjds.end(); mjdIter++) {
    do work.
}

It's not too lengthy, but it's hardly expository - at first glance it actually looks like a mistake!

Another solution is to have an "nth element" helper function, I guess. Any cooler ideas?

Answer

avakar picture avakar · Nov 18, 2010

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.