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?
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.
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 >, >=, <, <=.
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.
#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.
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