I was exploring priority_queue class in C++ and couldn't think about any practical use of swap().
Ref: http://www.cplusplus.com/reference/queue/priority_queue/swap/
Can someone list a practical example where it is beneficial to use this function. Essentially it feels like renaming the priority queue variable.
std::priority_queue<int> foo,bar;
foo.push (15); foo.push(30); foo.push(10);
bar.push (101); bar.push(202);
foo.swap(bar);
std::cout << "size of foo: " << foo.size() << '\n';
std::cout << "size of bar: " << bar.size() << '\n';
swap
is a library-wide feature; many of the classes in the standard library support swap. It's also a customization point; you can specialize std::swap
for your own classes.
As to what it's useful for - there's lots of algorithms that use it (all the sorting algorithms, for example) and some of the containers use it internally.
A swap
that is noexcept
is a great tool for writing exception-safe code.