std::vector<weight> decoy;
void clear_decoy() {
decoy.clear();
std::vector<weight>(decoy).swap(decoy);
}
In the above method clear_decoy()
, what does vector<weight>(decoy).swap(decoy);
mean please?
Does the method clear decoy
or not? Thanks!
It creates a new vector of Weight
objects (which will be empty) and swaps it with decoy
.
The reason for this is that by default, std::vector<t>::clear
often doesn't actually reduce the storage used by a vector, it merely destroys all the objects contained there. This way, the vector has room to store more objects without reallocation in the future.
Sometimes, however, you want to trim the capacity in the vector. Swapping with a newly created vector (which lives until the end of it's line, and is therefore destroyed there) frees all the memory allocated by the vector.