By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,227 Members | 1,241 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,227 IT Pros & Developers. It's quick & easy.

vector reserve() and clear()

P: n/a
vector<stringbuf_string;
buf_string.reserve(256);
vector<intbuf_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?

Nov 2 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a

pkirk25 wrote in message
<11**********************@f16g2000cwb.googlegroups .com>...
vector<stringbuf_string;
buf_string.reserve(256);
vector<intbuf_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?
--
Bob R
POVrookie
Nov 2 '06 #2

P: n/a
Very neat - many thanks! I didn't see the capacity member :-(

Nov 2 '06 #3

P: n/a
pkirk25 wrote:
vector<intbuf_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

Nov 6 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.