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::prevfunction: