Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop on last element iterators C++

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;
}
like image 643
user Avatar asked Jun 17 '12 18:06

user


2 Answers

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;
}
like image 143
R. Martinho Fernandes Avatar answered Nov 02 '22 05:11

R. Martinho Fernandes


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';
}
like image 23
ildjarn Avatar answered Nov 02 '22 05:11

ildjarn