I have a class of objects and need to compare one property of each object to the same property of all other objects. If they match, the code needs to do something. This results in two 'for loops' looping through the objects to get that property, and in the second 'for loop', there is a third 'for loop' going through the elements of the property (which is a vector) to compare them. If they match, I need the outer most 'for loop' to abort the current iteration and go on to the next one (I only want the first match with another object to be considered).
I have looked into 'goto' statements and into creating a do{}while() structure, but have not been able to implement them in a way to get the desired result. What I need is something like a 'continue' statement for the outer most loop based on what happens in the conditional statement in the inner most loop.
Which would be a good method to achieve this, and how would it have to be implemented?
Edit: Next to the answer I accepted, I would also recommend Martin Bonner's answer, which also works perfectly fine and doesn't rely on goto.
for (int i = 0; i < max; i++){
Object & object1 = system.getAgent(i);
VectorOfStrings object_property1 = object1.getProperty();
for (int j = i + 1; j < max; j++){
Object & object2 = system.getObject(j);
VectorOfStrings object_property2 = object2.getProperty();
for (unsigned int k = 0; k < object_property1.size(); k++){
if (object_property1[k] == object_property2[k]){
//do something
break; //this aborts the inner most loop
//Additionally, I need the outer most loop to move on one iteration
}
}
}
}
So if the conditional statement in the 'k' loop is met, I want the 'i' loop to abort the current iteration and move on to the next one.
Also, since I'm new, the code might be inelegant, but please focus on this specific problem in your answers! Unless a general restructuring of the code might be the solution to the problem of course :)
This may be implemented with goto
:
for (int i = 0; i < max; i++){
Object & object1 = system.getAgent(i);
VectorOfStrings object_property1 = object1.getProperty();
for (int j = i + 1; j < max; j++){
Object & object2 = system.getObject(j);
VectorOfStrings object_property2 = object2.getProperty();
for (unsigned int k = 0; k < object_property1.size(); k++){
if (object_property1[k] == object_property2[k]){
//do something
goto cnt; //this aborts the inner most loop
//Additionally, I need the outer most loop to move on one iteration
}
}
}
cnt:;
}
This is one of the rare cases when usage of goto
really simplifies code.