[英]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. 在外循环的第一次迭代中,计数器变量
j
从0
递增到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]
完成时, j
为3
。
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.