Does C++ have a built in such as part of STL to swap two numerical values instead of doing:
int tmp = var1;
var1 = var2;
var2 = tmp;
Something like this:
std::swapValues(var1, var2);
Where swapValues is a tem开发者_运维知识库plate.
Use std::swap
std::swap(var1, var2);
As Stephen says, use std::swap(var1, var2);
It's a templated function, so you can provide your own specialisations for specific classes such as smart pointers, that may have expensive assignment operators:
namespace std
{
template<>
void swap<MySmartPointer>(MySmartPointer& v1, MySmartPointer& v2)
{
std::swap(v1.internalPointer, v2.internalPointer);
}
}
// ...
std::swap(pointerA, pointerB); // super-fast!!!!1
There's also Boost Swap.
http://www.boost.org/doc/libs/1_43_0/libs/utility/swap.html
It overcomes some of the present limitations in the standard swap implementation. You still have to provide your own specializations if you want better efficiency for your types but you have a bit more latitude as to how to provide those specializations.
精彩评论