I am a beginner in c++ so I was trying to solve a problem at codeforces and I have to make a 2d vector that have rows = 't' column = 'n[i]' and I tried too make it.
But when I run the program it crashes with error "vector subscript out of range" and I don't know how to fix it.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int t;
cin >> t;
vector<int>n(t);
vector<vector<int>>x(t);
for (int i = 0; i < t; i++) {
cin >> n[i];
for (int j = 0; j < n[i]; j++) {
cin >> x[i][j];
}
}
return 0;
}
std::vector<int>n(t);constructs a vector withtintegers. The integers are default constructed (actually not sure, but anyhows...), they are initialized with0.std::vector<std::vector<int>>x(t);constructs a vector withtinner vectors. The inner vectors are default constructed, they are empty.Trying to access elements that do not exist in
cin >> x[i][j];invokes undefined behavior.x[i]is empty vectors.You can use the constructor that takes another paramter, the initial value. For
tsized inner vectors:Alternatively you could call
resize:Or
reserveandpush_back: