Reputation: 1210
I read many questions on this topic on stackoverflow. However, I couldn't find my answer in any of them. Hence, this question.
I have
vector< vector< int > > temp
I can reserve memory for outer vector :
temp.reserve(20);
Now, I want to reserve memory for each inside vector. I can do this using:
temp[i].reserve(500);
However, if I use temp.clear(); then the capacity of temp is retained as 20. However, now if I initialize the temp vector with 20 inner vectors, the capacity of these inner vectors is reset to 0 (according to VS2010 Intellisense).
My questions:
How can I retain the inner vector capacity of 500 even after I clear and re-initialize the outer vector?
I am using OpenCV findContours function. This function clears the outer vector and fills it with new set of inner vectors. Does this function cause deallocation and re-allocation of memory?
Upvotes: 3
Views: 772
Reputation: 96233
1) You can't in C++. Clearing the outer vector by definition destroys the inner vectors, releasing all their memory.
2) If it's clearing the outer vector and recreating it, then yes it's causing a deallocation followed by an allocation.
Unfortunately I can't make out what your underlying problem is so I can't offer any more help regarding possible solutions.
EDIT: You could always have outer be a vector of (possibly smart) pointers to inner vectors that are stored in/retrieved from a pool. Then when outer is cleared only the pointer itself is cleared and the pooled inner vector yet remains.
Upvotes: 1