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.
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++;
}
                        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