How do I break out of multiple loops?

EX: If "myVector" contains a random series of numbers and i have the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
do
{
    for(count=0;count<myVector.size();count++)
    {
        if(myVector.size()==3)
            //This is where I would want to break out of all of the loops
        else
        {
            ...
        }
        cout << endl;
        ...
        ...
    }
    ...
    ...
}
while(random!=2)


^^The above code is just an example. The "..." just represent random code
you COULD(but by no means should) use a goto statement.

works like this:

1
2
3
4
5
6
7
8
9
10
#include<iostream>
using namespace std;

int main{
goto here;
cout << "skip me" << endl;
here:
cout << "I'm here" <<endl;
return 0;
}



I'm here
I was trying to avoid that but I don't see any other way unless I can break out of all the loops
What about this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
try{
do
{
    for(count=0;count<myVector.size();count++)
    {
        if(myVector.size()==3)
                   throw 1;
         //This is where I would want to break out of all of the loops
        else
        {
            ...
        }
        cout << endl;
        ...
        ...
    }
    ...
    ...
}
while(random!=2)
}
catch(int a){
//do stuff
}
Almost as unstable as a goto loop
What is so unstable about it? Using try catch is very flexible. E.G. if you were to, say, declare dynamic memory inside the loop, you could instead throw a vector of pointers, and then delete the unfreed memory using the pointers in that vector within the catch statement.

Another option would be to make a boolean and have the loop exit when the boolean is false;
Or you could simply put your loop in a function, and return when your condition is met.
You could add an extra condition inside each for/while statement, otherwise goto is probably your best bet. I would argue that goto is better than try/catch since it makes more sense semantically. For an outside reader of your code, the try/catch stuff is going to be confusing because the assumption is that it represents unexpected or unwanted behaviour.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
do
{
    bool tryThis = false;
    for(count=0;count<myVector.size();count++)
    {
        if(myVector.size()==3)
        {
          tryThis = true;
          break;
        }     //This is where I would want to break out of all of the loops
        
        else
        {
            ...
        }
        cout << endl;
        ...
        ...
    }
    ...
    ...
  if (tryThis == true) break;
}
while(random!=2)

Topic archived. No new replies allowed.