Trimming Vector's Excess Capacity

L

leeps_my

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

Ian Collins

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?
 
B

benben

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
 
L

leeps_my

Duh on me. Resize-to-size does nothing on capacity.

Thanks, benben, and Ian too.


Regards,
leeps_my
 

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

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top