How can I skip elements in a range-based for loop based on 'index'?

Jay picture Jay · Jan 19, 2014 · Viewed 7k times · Source

Is there a way to access the iterator (I suppose there's no loop index?) in a C++11 range-based for loop?

Often we need to do something special with the first element of a container and iterate over the remaining elements. So I'm looking for something like the c++11_get_index_of statement in this pseudo-code:

for (auto& elem: container) 
{
  if (c++11_get_index_of(elem) == 0)
     continue;

  // do something with remaining elements
}

I'd really like to avoid going back to old-style manual iterator handling code in that scenario.

Answer

Ali picture Ali · Jan 19, 2014

Often we need to do something special with the first element of a container and iterate over the remaining elements.

I am surprised to see that nobody has proposed this solution so far:

  auto it = std::begin(container);

  // do your special stuff here with the first element

  ++it;

  for (auto end=std::end(container); it!=end; ++it) {

      // Note that there is no branch inside the loop!

      // iterate over the rest of the container
  }

It has the big advantage that the branch is moved out of the loop. It makes the loop much simpler and perhaps the compiler can also optimize it better.

If you insist on the range-based for loop, maybe the simplest way to do it is this (there are other, uglier ways):

std::size_t index = 0;

for (auto& elem : container) {

  // skip the first element
  if (index++ == 0) {
     continue;
  }

  // iterate over the rest of the container
}

However, I would seriously move the branch out of the loop if all you need is to skip the first element.