Sign in to follow this  
riruilo

question about std::vector and reserve or capacity

Recommended Posts

Hi! Just one question. I´m storing my objects pointers in a std::vector. I use push_back to add my pointers. My question is: Should I use reserve or capacity methods? or it is not neccesary. I mean, in a efficient point of view. By the way, I know the number of my elements and they are fixed. Thanks you very much!

Share this post


Link to post
Share on other sites
Every time your vector gets larger than the memory it has allocated it need to allocate new memory and copy over the objects. So if you know how many objects you are going to store, use reserve. It will most probably be more efficient.

Share this post


Link to post
Share on other sites
If you know how many elements you will be storing you can use reserve and then push_back them into the vector. It's a good habit to get into. You shouldn't need to use capacity during normal use.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this