假设您有一个双嵌套 for,例如当您试图查看一个未排序数组中的项目是否在另一个未排序数组中时。例如,假设您有 2 个列表 candidates
和 corruptPeople
,您正在浏览 candidates
并跳过 中列出的那些腐败的人
。
for( int i = 0 ; i < lenCandidates ; i++ )
{
// veto candidates[i] if candidates[i] is in corruptPeople at all
for( int j = 0 ; j < lenCorruptPeople ; j++ )
if( candidates[i] == corruptPeople[j] )
break_this_loop_and_then_continue_outer_loop ;
// initiate the eligible candidates
initiate( candidates[i] ) ;
}
最佳答案
一种方法(我愿意接受同行评审!)是使用 goto
:
for( int i = 0 ; i < lenCandidates ; i++ )
{
// veto candidates[i] if candidates[i] is in corruptPeople at all
for( int j = 0 ; j < lenCorruptPeople ; j++ )
if( candidates[i] == corruptPeople[j] )
goto END_FOR ;
// initiate the eligible candidates
initiate( candidates[i] ) ;
END_FOR:
; // seem to need an empty statement to make it compile
}
我很好奇其他人对在这种情况下使用 goto
有何看法。教条式地反对 goto
意味着你将有一个教条式的结构化编程应用程序……当我尝试时它看起来很糟糕。
关于从内部 for 循环中断开外部 for 循环的干净方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13756706/