I'm discovering C++11 range based loop and already love it. It makes you save lot of time when coding.
However, I'm used to writing some loops with extra statements/conditions and am wondering it this can be achieved when using C++11 range based-loop:
1. Extra incrementation
std::vector<int> v = { 1, 2, 3, 4, 5 };
size_t index = 0;
for ( std::vector<int>::const_iterator iter = v.begin(); iter != v.end(); ++iter, ++index )
{
std::cout << "v at index " << index << " is " << *iter;
}
Could become:
size_t index = 0;
for ( int val : v )
{
std::cout << "v at index " << index << " is " << *iter;
++index;
}
However, incrementing index in the for loop is better because guaranteed (incremented even if for loop has continue statements for example)
Is there a way to move ++index inside the for statement?
2. Get iteration index dynamically
std::vector<int> v = { 1, 2, 3, 4, 5 };
for ( std::vector<int>::const_iterator iter = v.begin(); iter != v.end(); ++iter )
{
std::cout << "v at index " << ( iter - v.begin() ) << " is " << *iter;
}
Can something similar be achieved with C++11 range-based loop? Is there a way to know how many iterations were done so far?
3. Extra exit condition
I often use this in code where break is forbidden as a coding guidline:
std::vector<int> v = { 1, 2, 3, 4, 5 };
bool continueLoop = true;
for ( std::vector<int>::const_iterator iter = v.begin(); iter != v.end() && continueLoop; ++iter )
{
std::cout << "v value is " << *iter;
if ( *iter == 4 )
continueLoop = false;
}
Can something similar be achieved with C++11 range-based loop (break exeuction without using a break)?
if (a) break; if (b) break; if (c) break;is much easier to read thanif (a) cont = false; else if (b) cont = false; else if (c) cont = false;[becausebandcshould not be executed whenais true, so we NEED to use else-if to make sure that doesn't happen]breakstatement to be used...I'm not using it, but there could be cases wherebreakis forbidden by company guidlines...switchstatement inside the loop. (To reuse thebreakkeyword there is one of those truly stupid syntactic decisions in the design of C that C++ inherited.)