search

Home  >  Q&A  >  body text

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

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

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

PHP中文网PHP中文网2807 days ago555

reply all(4)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 11:38:26

    In fact, it can be like this... When the number of loops is very large, it is more effective; because if you make a judgment once in each loop, it will be judged as many times as there are loops. It is better to skip this judgment directly.

    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
        }
    }
    

    reply
    0
  • 迷茫

    迷茫2017-04-17 11:38:26

    if(i==j)continue;

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 11:38:26

    You can use it in two ways, one is @sin’s kind

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

    Another way is:

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

    The former is more concise, especially when the logic is particularly complex, the advantages of the former are better reflected.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 11:38:26

    @sin’s answer is very good and the efficiency is also reflected.

    reply
    0
  • Cancelreply