tags:

views:

191

answers:

3

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 template.

+19  A: 

Use std::swap

std::swap(var1, var2);
Stephen
I agree with using std::swapWith the caveat that std::swap uses the copy constructors of whatever you are swapping. So bear in mind that it this is fine for primitive data types but once you start getting into larger structures and classes it becomes less efficient.http://www.cplusplus.com/reference/algorithm/swap/
C Nielsen
@C Nielsen, but you can use the usual idiom and specialise `std::swap` for expensive classes to avoid a temporary.
Alex B
Such larger objects can overload `std::swap` if there is a more efficient method available.
Dennis Zickefoose
@C Nielsen, @Alex B, give [How to overload `std::swap()`](http://stackoverflow.com/questions/11562/how-to-overload-stdswap) and [this ancient c.l.c++.m post](http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/b396fedad7dcdc81) for some interesting discussion about how to specialize `std::swap`.
D.Shawley
Thanks all, I won't add noise by editing the answer with the discussions about `swap` specializations - the comments and @tenpn's answer cover it fairly well. I'd also add that Scott Meyer's covers it in Effective C++. ( http://search.barnesandnoble.com/Effective-C/Scott-Meyers/e/9780321334879 )
Stephen
+5  A: 

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
tenpn
Make sure to read the discussions in the [How to overload `std::swap`](http://stackoverflow.com/questions/11562/how-to-overload-stdswap) question. This is a good approach but you have to be aware of the problems associated with it.
D.Shawley
+1  A: 

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.

Ken Smith