Need help.. Please tell me why ” A.clear() ” does not clear the first column too?
………………………………………………..
#include <iostream>
#include <vector>
using namespace std;
int N, M;
vector< vector<int> > A;
int main()
{
cin >> N >> M;
A.resize(N + 2);
for (int i = 0; i <= N; ++i)
{
A[i].resize(M + 2);
}
A.clear();
for (int i = 0; i <= N; ++i)
{
for (int j = 0; j <= M; ++j)
{
cout << A[i][j] << ' ';
}
cout << '\n';
}
return 0;
}
clearremoves all elements of the vector as opposed to setting all of them to 0 as you seem to be expecting. After calling clear the size of your vector is 0. Thus when you try to readA[i][j]you are accessing an index out of bounds and anything may happen(your code causesundefined behavior).