调整向量向量的大小

Resizing a vector of vectors

下面是调整向量向量大小的代码块。为每一行的大小生成的输出打印为 0?为什么即使我将每一行的大小都调整为 W,也会发生这种情况;

int main() {
    int H,W,i;
    cin >> H,W; // H=3,W=5;
    vector<vector<int> >v;
    v.resize(H);

    for(i=0;i<H;i++)
        v[i].resize(W);

    cout << v[1].size(); // Output is printed 0 
}

cin >> H,W; 没有达到您的预期。根据 C++ Operator Precedence, it's the same as (cin >> H), W;, the 2nd expression W does nothing in fact, so W is not initialized at all. Any usage of it would lead to undefined behavior.

改为cin >> H >> W;

顺便说一句:将 cout << v[1].size(); 更改为 cout << v[i].size();