std::vector Allocation - Quick Question
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?
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."
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)
So it would be better to precalculate size then, right? (Sorry for being a n00b, just don't know alot about memory theory)
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement