Prashant Cristiano Prashant Cristiano - 3 months ago 8
C++ Question

C++ vector not assigned values

I am writing a code in which if I am getting input of size of vector and then assigning the size of vector the vector is not getting values assigned which are inserted.

cin>>size;
vector<int> vec(size);
//vec.reserve(n);
for(int i=0;i<size;i++)
{
int x;
cin>>x;
vec.push_back(x);
}


If I am using "reserve" it's working fine what can be the reason. I am new to C++ so please don't come hard on me. Please tell me what can be the problem.
I just can't understand why all values of vector are zero instead of what given as input. Thanks for help in advance.

Answer
vector<int> vec(size);  // Creates a vector with "size" elements in it
vec.push_back(x);       // Adds a new element
vec.push_back(x);       // And another

Now you have "size+2" elements.

This is the same:

vector<int> vec;        // Creates an empty vector
vec.resize(size);       // Makes the vector have "size" elements in it
vec.push_back(x);       // Adds a new element
vec.push_back(x);       // And another

Let's look at your other attempt:

vector<int> vec;        // Creates an empty vector
vec.reserve(size);      // Reserves enough memory for "size" elements, but doesn't add them
vec.push_back(x);       // Adds the first element
vec.push_back(x);       // And another

Now you have 2 elements.

Do you see what is happening? This is all explained in your favourite std::vector documentation.


Your "reserve" approach is good, but you could also do this:

vector<int> vec(size);  // Creates a vector with "size" elements in it
vec[0] = x;             // Changes the value of the first element
vec[1] = x;             // Changes the value of the second element

Now you still have only "size" elements.