vector <weight> decoy;
void clear_decoy() {
decoy.clear();
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!
vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.
The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.
The C++ vector has many member functions. Two of these member functions are erase() and pop_back(). pop_back() removes the last element from the vector. In order to remove all the elements from the vector, using pop_back(), the pop_back() function has to be repeated the number of times there are elements.
C++ set clear() function is used to remove all the elements of the set container. It clears the set and converts its size to 0.
I've never seen that form before.
I have seen it written as:
vector<weight>().swap(decoy);
Which means "create a new empty vector, and swap it with the existing one.
vector<weight> (decoy).swap(decoy);
To understand that, break in to parts.
vector<weight>(decoy)
create a new vector (with it's contents copied from the now empty decoy). The new vector is an anonomous temporary, so let's pretent it's name is newvector
.
newVector.swap(decoy);
swaps the new vector with decopy.
(Updated per comments to fix bug)
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.
That code is a failed attempt to use a common trick to ensure the memory allocated by the vector is freed. It may or may not actually do that, depending on whether or not the vector's copy constructor allocates memory to match the other vector's size, or its capacity.
To reliably free the memory, use the following:
void clear_decoy() {
vector<weight>().swap(decoy);
}
This creates a temporary empty vector (with little or no memory allocated), swaps this with decoy
so that the memory is now owned by the temporary, then destroys the temporary, freeing the memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With