Possible Duplicate:
How to downsize std::vector?
It seems that std::vector will not release memory even I call pop_back(), clear() or resize().
Is there any good way to deal with this? For example, in the following code:
#include<vector>
using namespace std;
int main(){
int i, j;
vector<int> v[10000];
for( i=0 ; i<10000 ; i++ ){
for( j=0 ; j<100000000 ; j++ ){
v[i].push_back(j);
}
while(v[i].size()>0){
v[i].pop_back();
}
v[i].resize(1);
}
return 0;
}
The vector will not release any memory until it finished.
std::vectorgrows but never shrinks. The reason is that growing is expensive, so if you shrink and then grow back it’s a waste of performance.If you really want to shrink a large vector use the swap idiom:
This doesn’t guarantee the new size of
vecis exactly the sum of sizes of its elements, but it should be something close. Also, C++0x’sstd::vectorwill have ashrink_to_fit()member that will do roughly that.