469,898 Members | 1,755 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,898 developers. It's quick & easy.

vector reserve() and clear()

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
3 3936

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
Very neat - many thanks! I didn't see the capacity member :-(

Nov 2 '06 #3
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.

Similar topics

10 posts views Thread by Stefan Höhne | last post: by
10 posts views Thread by Huibuh | last post: by
10 posts views Thread by Bob | last post: by
8 posts views Thread by Alex Vinokur | last post: by
7 posts views Thread by Dilip | last post: by
17 posts views Thread by toton | last post: by
32 posts views Thread by T. Crane | last post: by
13 posts views Thread by smp | last post: by
3 posts views Thread by clinisbut | last post: by
1 post views Thread by Waqarahmed | last post: by
reply views Thread by Salome Sato | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.