Hello,
I am trying to see if there is a nicer way to break out of a double loop. I have the code
1 2 3 4 5 6 7 8 9 10 11
RAND = double(rand())/RAND_MAX;
double cum = 0;
for (row=0; row<NSrv+1; row++) {
for (col=0; col<NSrv+1; col++) {
cum += R[row][col];
if ( RAND < cum) {
goto end_loop;
}
}
}
end_loop:
I basically have a normalized martix, I throw a random number then stp through each matrix element and add the components. Once the cumulative sum is greater than my random number I want to stop this so I know both the row and column where this occurs. What I have above works, it compiles fine. When I run it, it gives me all this garbage and crap about libraries I think, but it actually runs and works fine. Is there a better way to break out of a double loop? On another note, does anyone know a better random number generator for c++ rather than rand()? I find it crazy that it is not uniform (0,1) but rather uniform in (0,RAND_MAX)!
Goto is just perfect for this job.. (I don't know why people hate it so much. With appropriate labels, its just so perfect for me at least). But if you want to eliminate it anyway.. you can do it as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13
bool Loop = true;
RAND = double(rand())/RAND_MAX;
double cum = 0;
for (row=0; row<NSrv+1 && Loop; row++) {
for (col=0; col<NSrv+1 && Loop; col++) {
cum += R[row][col];
if ( RAND < cum) {
Loop = false;
}
}
}
> I am trying to see if there is a nicer way to break out of a double loop
IMHO, a goto is one of the nicest ways to break out of deeply nested loops. (In C++ where a break statement cannot specify which loop to break out of.)
Thanks everyone for the help. Actually, I figured out what was wrong and what it was complainign to me about and it had nothing to do with my goto statement. It had to do with something I did to either row/col when it was a certain value after breaking out of the double loop. I guess now that I know this works, I am happy with the goto statement as it is the easiest/cleanest way to do this! Thanks again