首页 > C++ for循环如何排除一些循环值?

C++ for循环如何排除一些循环值?

for(int i=0;i<10;i++)
    for (int j=0;j<10;j++)

怎么实现第二个for循环里只产生不同于i的值?
比如i==0时,j19


可以用两种方式,一种就是 @sin 那种

for(int i=0;i<10;i++){
    for (int j=0;j<10;j++){
        if(i==j){
            continue;
        }
        //Paste your code here.
    }
}

另一种方式就是:

for(int i=0;i<10;i++){
    for (int j=0;j<10;j++){
        if(i==j){
            //Do nothing.
        }
        else{
            //Paste your code here.
        }
    }
}

前者更为简洁,尤其是当逻辑特别复杂的时候,前者的优势就更能体现。


@sin 的回答很好,效率也能体现。


其实还可以这样……在循环次数非常大的时候,比较有效;因为如果在每次循环里去判断一次,有多少次循环就会判断多少次,不如直接跳开这个判断。

const int max = 10;

for (int i = 0; i < max; i++) {
    for (int j = 0; j < i; j++) {
        // call function to do something
    }
    for (int j = i + 1; j < max; j++) {
        // call function to do something
    }
}

if(i==j)continue;

【热门文章】
【热门文章】