1

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

4 回答 4

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意味着你将有一个教条式的结构化编程应用程序。当我尝试它时看起来很糟糕。

于 2012-12-07T04:02:49.407 回答
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] ) ;
}
于 2012-12-07T04:08:35.850 回答
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] ) ;
    }

}
于 2012-12-07T04:13:02.223 回答
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] ) ;
    }
}
于 2012-12-07T04:43:24.837 回答