Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 578
user511493 Avatar asked Nov 18 '10 00:11

user511493


People also ask

How do you find the iterator of a vector element?

To get an iterator starting from the n'th item, the idea is to construct an iterator pointing to the beginning of the input vector and call the standard algorithm std::advance to advance the iterator by specified positions.

How do you compare two iterators?

we can use == and != to compare to valid iterators into any of the library containers. The section also tells us that iterators for string and vector support relational operators (aka iterator arithmetic) which include >, >=, <, <=.


2 Answers

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.

like image 113
avakar Avatar answered Sep 17 '22 09:09

avakar


#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.

like image 39
Steve Townsend Avatar answered Sep 20 '22 09:09

Steve Townsend