vector<int> a;
for(int i=0;i<5;i++)
{
a[i]=i;
}
I am a beginner and have just come across vectors in C++. I learned that we don't have to specify the size of vectors unlike the array beforehand. So, why can't I do this?
vector<int> a;
for(int i=0;i<5;i++)
{
a[i]=i;
}
I am a beginner and have just come across vectors in C++. I learned that we don't have to specify the size of vectors unlike the array beforehand. So, why can't I do this?
I learned that we don't have to specify the size of vectors unlike the array beforehand. So, why can't I do this?
Initialize the vector's size to be n
. Then you can use cin
like below -
int n;
cin>>n;
vector<int> a(n);//Vector declared with size
for(int i=0;i<n;i++)
cin>>a[i];
The reason behind this is - vectors grow in size dynamically, if you initialize their size in compile-time itself, you can definitely cin
the values. But if you don't initialize the size at compile-time then for vector to understand how much space to allocate you should use push_back
.
When you don't initialize the size n
at compile-time using vector<int> a;
there are no values at that location so you cannot use the []
operator as []
are for access not for resizing. And when you initialize it as vector<int> a(n);
the values are predominantly initialized with value 0
and since it is initialized you can use []
operator.
Further Reading -
Yes, you don't have to specify a vector size in some circumstances.
for(int i=0;i<5;i++)
{
a.push_back(i);
}
This increases the vector size, since you don't access vector's elements directory but ask to add new elements to the tail, and the vector class does job the best for you.