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

Trimming Vector's Excess Capacity

P: n/a
I'm thinking of using "resize-to-size" to do the trimming:

aVector.resize( aVector.size( ) );

I'm wondering why Scott Meyers was recommending "swap trick" instead,
since the trick involves construction and destruction of a temporary,
and might still leave some excess capacity in the vector.

Apr 23 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
le******@yahoo.com wrote:
I'm thinking of using "resize-to-size" to do the trimming:

aVector.resize( aVector.size( ) );

I'm wondering why Scott Meyers was recommending "swap trick" instead,
since the trick involves construction and destruction of a temporary,
and might still leave some excess capacity in the vector.

What problem are you trying to solve?

--
Ian Collins.
Apr 23 '06 #2

P: n/a
le******@yahoo.com wrote:
I'm thinking of using "resize-to-size" to do the trimming:

aVector.resize( aVector.size( ) );

I'm wondering why Scott Meyers was recommending "swap trick" instead,
since the trick involves construction and destruction of a temporary,
and might still leave some excess capacity in the vector.


I'm lost. The code you posted just doesn't do anything (non-trivial.)

A vector can reserve extra memory for future elements but resize wont
release this memory. If you feel really like to get rid of the extra
memory you can do a swap.

To demonstrate you can try to compile the following program and run it:

#include <iostream>
#include <vector>

int main()
{
using std::vector;
using std::cout;

vector<int> v(5);
v.reserve(20);

cout << "v.size() == " << v.size() << '\n'
<< "v.capacity() == " << v.capacity() << '\n';

// resize
cout << "\nHere I do the vector resize.\n";
v.resize(v.size());

cout << "v.size() == " << v.size() << '\n'
<< "v.capacity() == " << v.capacity() << '\n';

// swap
cout << "\nHere I do the vector swap.\n";
v.swap(vector<int>(v));

cout << "v.size() == " << v.size() << '\n'
<< "v.capacity() == " << v.capacity() << '\n';
}

Regards,
Ben
Apr 23 '06 #3

P: n/a
Duh on me. Resize-to-size does nothing on capacity.

Thanks, benben, and Ian too.
Regards,
leeps_my

Apr 23 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.