Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 599
Jay Avatar asked Jan 19 '14 11:01

Jay


1 Answers

How about using a simple for loop with iteratos:

for(auto it = container.begin(); it != container.end(); it++)
{
    if(it == container.begin())
    {
        //do stuff for first
    }
    else
    {
        //do default stuff
    }
}

It's not range based, but it's functional. In case you may still want to use the range loop:

int counter = 0;
for(auto &data: container)
{
    if(counter == 0)
    {
        //do stuff for first
    }
    else
    {
        //do default stuff
    }
    counter++;
}
like image 125
Netwave Avatar answered Sep 22 '22 13:09

Netwave