Reputation: 1
I understand that we can insert values in 2D vector as vec[i].push_back(value)
but I was trying to insert value in the 2D vector as vec[i][j] = value
, but it was giving the error :
Line 1034: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator>' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9
Ideally when we use a 1D vector we can assign values like a[i] = value
. But in 2D vectors why does C++ not allow assignment of values in 2D vector like this.
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<vector<int>> v;
int i,j,n = 3,m = 4,num;
for(i=0;i < n;i++){
for(j=0;j<m;j++){
cin>>num;
v[i][j] = num;
}
}
for(i=0;i < n;i++){
for(j=0;j<m;j++){
cout<<v[i][j]<<" ";
}
cout<<endl;
}
}
If it was a 2D array. We could do this operaion. But, why not in a vector. Can you please refer me a material to read about it ?
Upvotes: 0
Views: 126