C++ range based loop with special case for first item?

  • A+
Category:Languages

I find myself often with code that looks like this:

bool isFirst = true; for(const auto &item: items) {     if(!isFirst)      {         // do something        isFirst = false;     }     // Normal processing } 

Seems like there ought to be better way to express this as it's a common pattern in functions that act like "join".

 


You can't know which element you are visiting in a range based for loop unless you are looping over a container like an array or vector where you can take the address of the object and compare it to the address of the first item to figure out where in the container you are. You can also do this if the container provides lookup by value, you can see if the iterator returned from the find operation is the same as the begin iterator.

If you need special handling for the first element then you can fall back to a traditional for loop like

for (auto it = std::begin(items), first = it, end = std::end(items); it != end; ++it) {     if (it == first)     {         // do something     }     // Normal processing } 

If what you need to do can be factored out of the loop then you could use a range based for loop and just put the processing before the loop like

// do something for(const auto &item: items) {     // Normal processing } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: