清洁方式从内部循环打破外部循环

时间:2012-12-07 04:00:42

标签: c nested-loops

假设您有一个双嵌套,就像当您试图查看一个未排序数组中的项是否在另一个未排序数组中时。例如,假设您有2个列表candidatescorruptPeople,那么您将浏览candidates并跳过corruptPeople中列出的列表。

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] ) ;
}

4 个答案:

答案 0 :(得分:3)

这样做的一种方法(我可以通过同行评审!)正在使用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的教条不同意味着你将会有一个结构化编程的教条式应用......当我尝试它时看起来非常糟糕。

答案 1 :(得分:2)

使用额外的变量比使用goto更好:

for( int i = 0 ; i < lenCandidates ; i++ )
{
    // veto candidates[i] if candidates[i] is in corruptPeople at all
    int corrupt = 0;
    for( int j = 0 ; j < lenCorruptPeople ; j++ )
        if( candidates[i] == corruptPeople[j] )
        {
            corrupt = 1;
            break;
        }

    // initiate the eligible candidates
    if (!corrupt) initiate( candidates[i] ) ;
}

答案 2 :(得分:0)

下面的代码怎么样?我错过了什么吗?

for( int i = 0 ; i < lenCandidates ; i++ )
{
    // veto candidates[i] if candidates[i] is in corruptPeople at all
    int j;
    for( j = 0 ; j < lenCorruptPeople ; j++ )
    {
        if( candidates[i] == corruptPeople[j] )
          break;
    }

    //j will be equal to lenCorruptPeople only when candidate is not in corrupt list   
    if(j==lenCorruptPeople)
    {
        initiate( candidates[i] ) ;
    }

}

答案 3 :(得分:0)

将内循环移动到另一个函数通常会有所帮助:

typedef int Person; // or whatever it is.

Person *findPerson(Person *first, Person *last, Person val)
{
    while (first != last)
    {
        if (val == *first) return first;
        ++first;
    }
    return 0;
}

...

for( int i = 0 ; i < lenCandidates ; i++ )
{
    // veto candidates[i] if candidates[i] is in corruptPeople at all
    if (!findPerson(corruptPeople, corruptPeople+lenCorruptPeople, candidates[i]))
    {
        // initiate the eligible candidates
        initiate( candidates[i] ) ;
    }
}