简体   繁体   English

c ++中2d向量的cout缺少行

[英]missing rows with cout for 2d vector in c++

I am quite insane, and cannot interpret what happens here. 我很疯狂,无法解释这里发生的事情。

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

int main() {
    int i = 0, j = 0, m = 3, n = 3;
    vector<vector<int> > vvi(3, vector<int>(3, 1));

    // why the following code outputs only single row, 
    // i.e.,"111" from vvi[0]? what about vvi[1], vvi[2]?
    for(; i < m; ++i) {
        for(; j< n; ++j) {
            cout << vvi[i][j];
        }
    }
    // any difference from the code below? 
    // for(int i=0; i < m; ++i) {
    //   for(int j= 0; j< n; ++j) {
    //      cout << vvi[i][j];
    //   }
    // }
}

In the first iteration of the outer loop the counter variable j gets incremented from 0 to n , but since it never gets reset to 0 it stays at n , thus the inner loop condition j < n is false for all subsequent iterations of the outer loop. 在外循环的第一次迭代中,计数器变量j0递增到n ,但是由于它从未被重置为0所以它保持在n ,因此内循环条件j < n对于外循环的所有后续迭代都是false 。 Therefore the cout will never be executed again. 因此, cout将永远不会再次执行。

In the code you commented out, j gets reset (reinitialized) to 0 for every iteration of the outer loop and therefore it will print all rows. 在您注释掉的代码中,外循环的每次迭代将j重置(重新初始化)为0 ,因此它将打印所有行。

In the first one, when vvi[0] is done, j is 3 . 在第一个中,当vvi[0]完成时, j3
When it goes to vvi[1] j is still 3 so j < n is false. 转到vvi[1] j仍为3因此j < n为假。

In the second one, when the outer loop starts the second iteration, j will be set to 0 again. 在第二个中,当外循环开始第二个迭代时, j将再次设置为0

This code is equivalent with the second one(in the result): 此代码与第二个代码等效(结果中):

    for(; i < m; ++i) {
        for(j = 0; j< n; ++j) {
            cout << vvi[i][j];
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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