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);
}
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With