我很疯狂,无法解释这里发生的事情。
#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];
// }
// }
}
最佳答案
在外循环的第一次迭代中,计数器变量 j
从 0
递增至 n
, 但因为它永远不会重置为 0
它停留在 n
,因此内部循环条件 j < n
对于外循环的所有后续迭代都是假的。因此 cout
永远不会再执行。
在您注释掉的代码中,j
重置(重新初始化)为 0
对于外循环的每次迭代,因此它将打印所有行。
关于c++ - c++ 中二维 vector 的 cout 缺失行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35154918/