std::vector Allocation - Quick Question

Started by
3 comments, last by deadimp 18 years, 10 months ago
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?
Projects:> Thacmus - CMS (PHP 5, MySQL)Paused:> dgi> MegaMan X Crossfire
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."

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

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)
Projects:> Thacmus - CMS (PHP 5, MySQL)Paused:> dgi> MegaMan X Crossfire
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.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

Alright. Thanks for your help.
Projects:> Thacmus - CMS (PHP 5, MySQL)Paused:> dgi> MegaMan X Crossfire

This topic is closed to new replies.

Advertisement