Hello,
Scott Meyer's explains in "Effective STL" how to use the
std::vector's swap() method to shrink vectors. Perhaps this is relevant for
you. It works as follows:
// Creating a vector
std::vector<int> my_vec(arbitrary_small_number);
// Using it for huge settings
my_vec.reserve(huge_number);
for(int i = 0; i < huge_number; ++i)
my_vec.push_back(i);
// (Above code can be done more efficiently using std::generate, but that's
irrelevant)
// Do something with the vector
my_do_something_function(my_vec);
// Now we need the vector object, but not its elements
{
// We create a tiny vector
std::vector<int> my_tmp_vec(arbitrary_small_number);
// We swap the vectors
my_vec.swap(my_tmp_vec);
// Implicitly, my_tmp_vec's destructor called. Presumably, the allocator
gains all of its memory.
}
// At this point my_vec is truly small (which is waht we wanted).
I hope this helps,
Ami
P.S. Scott Meyer writes excellent books; even if this example doesn't help
you, I highly recommend his writings.
"Joseph Turian" <tu****@gmail.com> wrote in message
news:11**********************@c13g2000cwb.googlegr oups.com...
Fellow hackers,
Is it possible to shrink the capacity of a vector?
i.e. Without new'ing and delete'ing a vector, can one return its memory
to the heap?
Here's what I get under the g++ implementation:
vector<double> v = vector<double>(1024*1024);
cerr << v.capacity() << "\n"; // outputs 1048576
v.clear();
cerr << v.capacity() << "\n"; // outputs 1048576
v = vector<double>();
cerr << v.capacity() << "\n"; // outputs 1048576
Joseph