Hi all,

I came across some vector problem recently. Below is my code.

std::vector<int> MyBuffer(10);
for(int i=0;i<10;i++)
MyBuffer.push_back(i);//First 10 elements are zero and after index 10 i getting stored.


Why the behaviour if like this if i provide size during Declaration.


I want to know what will be the difference if I declare in the following method.
std::vector<int> MyBuffer;
MyBuffer.reserve(10);

Member Avatar for iamthwee

Vectors are supposed to be dynamic containers. Why specify the size before compilation, defeats the point.

In your posted code, because you used the constructor argument, it will allocate space for 10 int objects in the vector and initialise them all to 0.
Then in your for loop, you're pushing back 10 more int values (remember push_back pushes additional objects into the end of the vector) ranging from 0 to 9.
So your vector will contain 20 ints (10 which are initialised to 0, plus 10 more containing the values 0..9)

Whereas if you use the reserve() function, the difference is that the vector will allocate space for 10 ints, but their values will not be initialised. In other words, it will have allocated space for 10 ints, but the vector initially holds no actual values, it is empty.
So because the vector is empty, if you use push_back to add some ints, the values will be added from the start of vector. So you'd end up with a vector which contains the values 0..9.

I hope I've explained that clearly enough!

ok..So basically we should not specify the size when declaring the vectors.

Thank you JasonHippy.

It depends on how you intend to use the vector.

In general, however, NO you don't want to specify a vector's size when you declare it. There are very few situations that REQUIRE the vector to be initialized immediately.

Could you copy paste your code and just wrap it around so we can see it and we could help you out in more depth??

commented: Don't think we don't see through that one, cheater. -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.