the_naive the_naive - 4 months ago 15
C++ Question

How to stop a for loop by advancing the std::map iterator?

I'm iterating through a

std::map
twice through using an outer
for
loop and a nested
for
loop. I want stop the inner loop when the condition is met. I know that if I call break, it will stop both the loops. I don't want that. I only want to stop the inner
for
loop.

My code snippet is as below:

for(auto markerCounter = ellipsePropertiesMap.begin(); markerCounter != ellipsePropertiesMap.end(); markerCounter++)
{
for(auto markerCounter2 = ellipsePropertiesMap.begin(); markerCounter2 != ellipsePropertiesMap.end(); markerCounter2++)
{
if(conditionMet)
std::advance(markerCounter2, ellipsePropertiesMap.size());
//I also tried the following:
//markerCounter2 = ellipsePropertiesMap.end();
//markerCounter2++;
}
}


I'm trying to stop the inner for loop by advancing the iterator by the size of the std::map, but it's not working. I also tried to get the ending iterator and advance it to end the loop. Apparently that isn't working either.

So, how can I actually stop the inner loop?

Thanks.

Answer

I want stop the inner loop when the condition is met.

break will do that exactly.

Alternatively, you might be able to make that condition part of the loop-condition.

I know that if I call break, it will stop both the loops.

You knew wrong.


std::advance(markerCounter2, ellipsePropertiesMap.size());

This would be valid if and only if markerCounter2 == ellipsePropertiesMap.begin(). If the condition is satisfied on any other iteration than the first, you increment the iterator past the end and have undefined behaviour. Also, this iterator advancement doesn't break out of the loop body, which will be executed before the loop-condition is checked for the next time.

markerCounter2 = ellipsePropertiesMap.end();

This would dis-satisfy the loop condition, causing the loop to stop at the end of current iteration. However executing

markerCounter2++;

after it would again increment past the end and have UB.

Comments