I know that the vector is a dynamic array so you can enter values as you want. But in this code bellow the code crashes before I insert any value in the vector !! I don't know what I am doing wrong and I am new in programming. I tried to give it a size but it is not working.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int H,W;
cin >> H >> W;
vector <vector <int>> A;
for (int i = 0; i < H; i++)
for (int j = 0; j < W; j++)
cin >> A[i][j];
return 0;
}
You are reading values to A[i][j]
while the vector A
has no elements.
You have to allocate elements to read something there.
To allocate beforehand, you can use constructors.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int H,W;
cin >> H >> W;
// allocate H W-element vectors
vector <vector <int>> A(H, vector <int>(W));
for (int i = 0; i < H; i++)
for (int j = 0; j < W; j++)
cin >> A[i][j];
return 0;
}
Alternatively, you can insert elements via push_back()
.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int H,W;
cin >> H >> W;
vector <vector <int>> A;
for (int i = 0; i < H; i++)
{
vector <int> row;
for (int j = 0; j < W; j++)
{
int value;
cin >> value;
row.push_back(value);
}
A.push_back(row);
}
return 0;
}
User contributions licensed under CC BY-SA 3.0