-1
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?

2 Answers2

2

I learned that we don't have to specify the size of vectors unlike the array beforehand. So, why can't I do this?

Solution

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 -

How Vectors Grow

anirudh
  • 1,436
  • 5
  • 18
  • 2
    You may want to reword **not for writes**. You certainly can use `[]` for writing. You just cannot resize with `[]`. – user4581301 Jul 04 '21 at 06:25
  • 1
    In addition to the concern raised by user4581301, the wording "pre-define" and "declaring" a vector with a size is incorrect. The correct description is that `vector a(n)` *initialises* the vector's size to be `n`. Declaring means something else entirely in C++, and a definition is a type of declaration. The fact that `vector a(n)` defines (and declares) `a` doesn't mean that the size is declared or defined to be `n`. – Peter Jul 04 '21 at 06:58
  • Thank you Peter & @user4581301 ,I have made the edits & I will be more careful while writing answers. Thanks a lot for your suggestions – anirudh Jul 04 '21 at 07:06
1

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.

273K
  • 29,503
  • 10
  • 41
  • 64