从内部 for 循环中断开外部 for 循环的干净方法

标签 c nested-loops

假设您有一个双嵌套 for,例如当您试图查看一个未排序数组中的项目是否在另一个未排序数组中时。例如,假设您有 2 个列表 candidatescorruptPeople,您正在浏览 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/

相关文章:

关于C中union的代码片段问题

c - 解析 C 中的命令行条目 : implementing a shell

c - 在 C 编程中,为什么我的 printf 在循环后不打印?

c# - 最佳实践 : Nested ForEach

java - 莫尔斯电码翻译器 - 似乎无法准确地从莫尔斯电码转换为英语

c - 为什么打印出错误的数组值?

c - 从可利用程序运行时出现 Shellcode Segmentation Fault 错误

java - Do-While 循环中的异常线程

PHP:优化数组迭代

java - java用正则表达式匹配字符串数组内容