Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in C++, I know that I can create for loops with multiple "loop expression>

C++
// simple straight-ish C++ loop
std::vector<Potato> potatoVector;
// fill vector with some potatoes
std::vector<Potato>::iterator it = potatoVector.begin();
int index = 0;
for ( it ; it != potatoVector.end() ; ++it, ++index )
{
  // do something with potatoes.. and the index...
}


Now, if I want to modernize this, I would do something like this (C++11)

C++
int index = 0;
for ( auto potato : potatoVector, ++index )
{
  // do something.
}


But that does not compile; it seems I cannot add loop expression in that kind of loop.

Is there a better way/pattern to do that ?
or is the following code the only way to do it (add the index increment in the loop block )?

C++
int index = 0;
for ( auto potato : potatoVector )
{
  // do something.
  ++index;
}


Thanks

Max.
Posted

1 solution

Hey lazy man :-), I suppose the ranged for syntax[^] gives you no escapes, you have to go with the ++index; in the curly braces.

BTW: often what do you really want to do is
C++
for ( auto & potato : potatoVector)

or
C++
for ( const auto & potato : potatoVector)
 
Share this answer
 
v2
Comments
Maciej Los 28-Nov-14 11:10am    
+5!
Maximilien 28-Nov-14 11:15am    
Thanks CP..
I know about the const and/or the & ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900