vector reserve() and clear()

P

pkirk25

vector<string> buf_string;
buf_string.reserve(256);
vector<int> buf_mat_prices;
buf_mat_prices.reserve(1000);

During loops I fill the vectors and then I empty them with commands
like buf_string.clear();
buf_mat_prices.clear();

Does this mean that the memory allocation returns to default or is my
original reserve still in place?
 
B

BobR

pkirk25 wrote in message
vector<string> buf_string;
buf_string.reserve(256);
vector<int> buf_mat_prices;
buf_mat_prices.reserve(1000);

During loops I fill the vectors and then I empty them with commands
like buf_string.clear();
buf_mat_prices.clear();

Does this mean that the memory allocation returns to default or is my
original reserve still in place?


// Prove it for yourself: // using std::cout;
cout << buf_string.size() << std::endl; // S/B '0'
cout << buf_string.capacity() << std::endl; // clear() doesn't resize

cout << buf_mat_prices.size() << std::endl; // S/B '0'
cout << buf_mat_prices.capacity() << std::endl; // clear() doesn't
resize

You can re-size the vector by using (surprise!):

buf_string.resize(25);
cout << buf_string.size() << std::endl;
cout << buf_string.capacity() << std::endl;

That help?
 
M

Michiel.Salters

pkirk25 said:
vector<int> buf_mat_prices;
buf_mat_prices.reserve(1000);
buf_mat_prices.clear();

Does this mean that the memory allocation returns to default or is my
original reserve still in place?

No, you still have the reservation. To "unreserve" you need to do a
swap-with-new:

vector<int>( ).swap(buf_mat_prices).

The vector<int>( ) is a temporary that gets the 1000 reservation, and
then dies.
buf_mat_prices gets the capacity of the freshly constructed temporary.

HTH,
Michiel Salters
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top