What is the most elegant way to perform a loop and stop after the second to last element (in C++11)?
Note: I mean for bidirectional iterators; random access iterators are a trivial special case, of course, because they have +
and -
operators.
std::list<double> x{1,2,3,4,5,6};
for (auto iter = x.begin(); iter != x.end(); ++iter) {
auto iter2 = iter;
++iter2;
if (iter2 == x.end()) break;
std::cout << *iter << std::endl;
}
Use the std::prev
function:
std::list<double> x{1,2,3,4,5,6};
for (auto iter = x.begin(); iter != std::prev(x.end()); ++iter) {
std::cout << *iter << std::endl;
}
In C++03 it would have been:
for (std::list<double>::iterator it = x.begin(), it_last = --x.end();
it != it_last; ++it)
{
std::cout << *it << '\n';
}
In C++11, there's nothing fundamentally different, it's just less verbose..:
for (auto it = begin(x), it_last = --end(x); it != it_last; ++it)
{
std::cout << *it << '\n';
}
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