Vector does reallocation on every push_back
Posted
by Amrish
on Stack Overflow
See other posts from Stack Overflow
or by Amrish
Published on 2010-04-27T19:47:31Z
Indexed on
2010/04/27
19:53 UTC
Read the original article
Hit count: 222
IDE - Visual Studio 2008, Visual C++
- I have a custom class Class1 with a copy constructor to it.
- I also have a vector
- Data is inserted using the following code
Class1* objClass1; vector<Class1> vClass1; for(int i=0;i<1000;i++) {
objClass1 = new Class1(); vClass1.push_back(*objClass1); delete objClass1; }
Now on every insert, the vector gets re-allocated and all the existing contents are copied to new locations. For example, if the vector has 5 elements and if I insert the 6th one, the previous 5 elements along with the new one gets copied to a new location (I figured it out by adding log statements in the copy constructors.)
On using reserve(), this however does not happen as expected! I have the following questions
- Is it mandatory to always use the reserve statement?
- Does vector does a reallocation every time I do a push_back; or does it happen because I am debugging?
© Stack Overflow or respective owner