Which way is better/faster in c++11 to clear a container (e.g. queue):
void clean()
{
std::queue<int> empty_q;
std::swap(q_to_clear, empty_q);
}
or using operator=(Q &&) (faster than swap ?)
void clean ()
{
q_to_clear = std::queue<int>{};
}
Or is it essentially the same ?
The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables. Parameters: The function accepts two mandatory parameters a and b which are to be swapped. The parameters can be of any data type.
deque::clear() The clear() function is used to remove all the elements of the deque container, thus making its size 0.
queue::swap() in C++ STL queue::swap() swap() function is used to exchange the contents of two queues but the queues must be of same type, although sizes may differ. Syntax: queue1. swap(queue2) OR swap(queue1, queue2) Parameters: queue1 is the first queue object.
It probably makes almost no difference at all, but the move-assignment requires that the temporary source queue needs to build a new, empty state after having been moved-from, which you can avoid with the swapping. And you can write the swapping as follows:
std::queue<int>().swap(q_to_clear);
C++11
-ness raised to extreme:
decltype(q_to_clear)().swap(q_to_clear);
Works on other std::
containers too.
and compact memory syntax is as cool as:
decltype(q_to_compact)(q_to_compact).swap(q_to_compact);
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