Using swap to effectively clear vector

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
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.
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.
The value of capacity() is always implementation defined
Topic archived. No new replies allowed.