Jump to content
  • Advertisement
Sign in to follow this  
deadimp

std::vector Allocation - Quick Question

This topic is 4869 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a small quesiton about the class std::vector (using the default allocator). Whenever the user calls push_back(), or something else that changes the amount of memory the vector occupies, what all is allocated/deallocated? Does it simply tack on some more memory at the end of the array, or does allocate a new vector, copy the data from the old to the new, and delete the old one? I'm asking this because I need to know if it would be better to limit the number of calls to push_back() to one, since I can precalculate it (but it will cost me twice as many loops), or would it be faster if I simply allocatd as I went along?

Share this post


Link to post
Share on other sites
Advertisement
If capacity() == size() then it allocates a new buffer, typically 1.5x as large as the previous, and copies the old data to the new. You can't just "tack on more memory at the end of the array."

Share this post


Link to post
Share on other sites
Thanks. That part has been confusing me for some while.
So it would be better to precalculate size then, right? (Sorry for being a n00b, just don't know alot about memory theory)

Share this post


Link to post
Share on other sites
Profile it and see. As the number of items that go into the vector grows, the fewer allocations it will need to make. On the other hand, if you know the exact size it will need to be before hand, then you can just do a reserve(). If you don't, then fill the vector and do something like: std::vector<T>(myvec).swap(myvec) which will shrink it to the size of the data in myvec (assuming you don't need to make any further inserts.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!