Using swap to effectively clear vector

Nov 29, 2010 at 6:53pm
vector::swap can be used to effectively free allocated memory. ie,

vector<int> v;
vector<int>().swap(v);

Maybe someone can explain why this is better then to use clear()?

thanks
Nov 29, 2010 at 7:18pm
It isn't better.
v.clear() would simply do what it says: destroy all the elements of v (in linear time)
vector<int>().swap(v); does the same in a more obfuscated way: swap the buffers of the temporary vector and the old vector (constant time), destruct the temporary vector (linear time)
Using swap may add some minor overhead caused by the construction and destruction of the temporary vector.
Nov 29, 2010 at 7:35pm
But the memory is not freed if you use clear. (the capacity remains the same)
So you could use swap if you want to shrink your memory usage.
Nov 29, 2010 at 8:53pm
The value of capacity() is always implementation defined
Topic archived. No new replies allowed.