简体   繁体   English

如何在C++中访问向量元素的向量?

[英]How to access the vector of vector element in C++?

#include<bits/stdc++.h>
#include<vector>
using namespace std;
int main(){
    
    int n=5;
    vector<vector<int>> v;
    v[0][0]=1;
    v[1][0]=1;
    v[1][1]=1;
    cout<<2;    //not getting output 2

}

In the above code I am trying to make a dynamic 2D array but the thing is that I am not getting any error but the number 2 is also not getting printed.在上面的代码中,我试图创建一个动态 2D 数组,但问题是我没有收到任何错误,但数字 2 也没有打印出来。 What may be the reason?可能是什么原因?

The default constructor of vector creates an empty vector. vector 的默认构造函数创建一个空向量。 You are accessing vector elements beyond the vector size which is Undefined Behavior.您正在访问超出矢量大小的矢量元素,这是未定义的行为。

You can initialize the vector with initializer lists:您可以使用初始化列表初始化向量:

std::vector<std::vector> v{
   {1},
   {1, 1}
};

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

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