I'm having a hard time grasping the use of break inside a loop. I know that in switch cases, the objective to tell the compiler to not get into that case.
Now in forloops I thought it was to tell the compiler to break the loop and go back out. I came up with a problem that was solved by using the break at the end of a for loop here is the code:
if( familyButton->isLoadingCompleted == true){// once we have finished the loader in our button. we reset some values
attractorCounter = 6;// switch our counter back to 4.
families->changeBoidStateToZero();// this function switches the boidState to 0 and makes sure the particles go back to screen.
//we also send the notes that are being selected
if ( bottle->bottleLabels.size() > 0 ){// we check if the size of the vector is 0
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvv This was making the compiler crash
vector<BottleButtonLabel>::iterator it;
for (it = bottle->bottleLabels.begin(); it != bottle->bottleLabels.end(); it++){
it = bottle->bottleLabels.erase(it);
break;// this fixed the compiler from crashing.
}
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^ This was making the compiler crash
if (families->returnFamilySelected() != -1) {
int i = families->returnFamilySelected();
for (int j = 0; j < notes[i]->boidList.size(); j++){
if (notes[i]->boidList[j]->boidState != 0){
notes[i]->boidList[j]->boidState = 0;
}
}
}
familyButton->isLoadingCompleted == false;// and switch the main condition back to false so we don't go back here.
}
Is there any reason why in that particular part of the code, it avoided the compiler from crashing? I thought the if statement that was checking for the size of the vector will do the house keeping and tell the compiler to not go once an element was deleted.
I will appreciate some clarification on the concept.
on line 12: if you erase the last element (without break) the next thing happens (on line 10): it++. This mean you're beyond bottle->bottleLabels.end() and it != bottle->bottleLabels.end() cannot apply anymore. So it's likely that you erase elements that are not in the vector -> crash.
The loop on line 10 doesn't make sense with the break. It erases only the first element not more. To erase them all call clear():