In fact, I have millions of vector objects in my program. By default, for each vector, the system assigns more space than it actually needs, since these vectors are read-only after loading is complete.
So, I want to reduce my ability to save memory. a typical way is to use the vector.swap () method as described in this question :
std::vector<T> tmp(v);
I tried this code, but found that the .swap() operation does not reduce the actual memory cost. (I looked at the size of the personal working set in the task manager to get the process memory usage)
Why is this? UPDATE " I use VS 2008, and I added a few lines to display the current capacity at runtime. As can be seen from the code below and its output, vec.capacity was reduced to 10 after swapping, but this is not reflected in the task manager.
Or maybe, as @Adam Rosenfield said, this change did not return the freed up OS space? Or should I not use the task manager to find its memory? I hope this swap () operation can have the same effect as delete pointer_to_a_big_vec , which will free memory directly.
My test sample is here:
void vecMemoryTest() { vector<int> vec; //make it big! for(int i = 0; i <= 100000; i++){vec.push_back(i);} for(int i = 0; i <= 100000; i++){vec.push_back(i);} cout << "Before .resize() : " << vec.capacity() << endl; //OK now I only need the first 10 elements vec.resize(10); cout << "After .resize() : " << vec.capacity() << endl; //So try to free other spaces vector<int> tmp(vec.begin(), vec.end()); vec.swap(tmp); // now should free wasted capacity // But in fact it doesn't cout << "After .swap() : " << vec.capacity() << endl; }
and output:
Before .resize (): 207382 After .resize (): 207382 After .swap (): 10
Jxitc source share