简体   繁体   中英

Different results depending on the location of for loop's looping index in C++

  size_t j = 1; size_t i = 1;

  for (i=1;i<=a;i++){
    for (j=1;j<=b;j++){
      board[i][j] = std::min( std::min(board[i - 1][j] + 1,board[i][j - 1] + 1),
                                          board[i - 1][j - 1] + (A[i - 1] == B[j - 1] ? 0 : 1) );
                                          //cout << board[i][j] << endl;
    }

  }
  cout << board[a][b] << endl;

So I'm just learning C++: if you look at the code above, i and j are defined as first parameters of two for loops. Because I declared i and j prior to this, I believe I can do this as well:

for (;i<=a;i++
  for (;j<=b;j++)

which in my entire code produces erroneous results. The first works correctly, however. Can anyone throw some light on this? thanks in advance

And I already did a search on this and am aware of the difference in scope of the index variable.

It's because of scope, basically, in your original code the j variable is reset to one at every iteration of the first loop: the for (j=1;....) . However, in the second version of your code, there is no reset.

In your first example, i starts at 1 and is incremented until it reaches the value of a. j starts at 1 and is incremented until it reaches the value of b.

You seem to think the first loop happens, and then the other loop happens. That is incorrect. The j-loop iterates b-times for every iteration of the i-loop . Because the first thing that happens on each iteration of the outer loop is j is set back to 1, you have no problems.

In your second example, i starts at 1 and is incremented until it reaches the value of a, just like before. j starts at 1 and is incremented until it reaches the value of b, which happens in the first iteration of the outer loop. On the second iteration of the outer loop, i is incremented to 2, but j has not been set back to 1, so it is incremented to whatever b is, and then b+1 on the next iteration of i, etc.

To make them equivalent, you'd need to set j to 1 in the body of the outer loop, just before the inner loop:

  size_t j = 1; size_t i = 1;

  for (;i<=a;i++){
    j = 1;
    for (;j<=b;j++){
      board[i][j] = std::min( std::min(board[i - 1][j] + 1,board[i][j - 1] + 1),
                                          board[i - 1][j - 1] + (A[i - 1] == B[j - 1] ? 0 : 1) );
                                          //cout << board[i][j] << endl;
    }

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM