4

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.

WilliamKF
  • 41,123
  • 68
  • 193
  • 295

3 Answers3

23

Use std::swap

std::swap(var1, var2);
Stephen
  • 47,994
  • 7
  • 61
  • 70
  • 3
    I agree with using std::swap With 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 Jul 10 '10 at 14:16
  • 3
    @C Nielsen, but you can use the usual idiom and specialise `std::swap` for expensive classes to avoid a temporary. – Alex B Jul 10 '10 at 14:26
  • Such larger objects can overload `std::swap` if there is a more efficient method available. – Dennis Zickefoose Jul 10 '10 at 14:29
  • 1
    @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 Jul 10 '10 at 14:36
  • 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 Jul 10 '10 at 15:09
5

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
  • 4,556
  • 5
  • 43
  • 63
  • 3
    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 Jul 10 '10 at 14:33
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.

Ken Smith
  • 775
  • 5
  • 11