Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do vectors declared without size need push_back to accept inputs with cin?

Tags:

c++

Why is it that a vector with declared size can accept input directly from cin like so:

int n;
cin>>n;
vector<int> a(n);//Vector declared with size
for(int i=0;i<n;i++)
    cin>>a[i];

But a vector declared without a size needs a push_back() function to accept inputs like:

int n;
cin>>n;
vector<int> a;//Vector declared WITHOUT size
int input;
for(int i=0;i<n;i++){
    cin>>input;
    a.push_back(input);
}
like image 964
srip Avatar asked Aug 31 '25 10:08

srip


2 Answers

The use of the [] operator on a vector assumes that the object at the given index is valid. If your vector hasn't allocated its internal buffer to fit this index, this is undefined behavior. Alternatively, the push_back() simply appends onto the end of the vector and reallocates a larger internal buffer if one is needed, so it never performs undefined behavior in the same way. By explicitly resizing your vector prior to accessing it with [], the array is resized such that accessing elements 0 to n-1 is defined, but anything beyond n-1 is undefined behavior.

like image 59
alter_igel Avatar answered Sep 03 '25 01:09

alter_igel


In the first example code your using vector constructor reserving place for n-elements, and you can use random access operator. Random access operator is not checking size of memory.

In second code you're creating empty vector. push_back is needed for additional step of memory allocation for an int object.

cpp reference with constructor functions: http://en.cppreference.com/w/cpp/container/vector/vector look in (3)

like image 37
paweldac Avatar answered Sep 03 '25 01:09

paweldac