(C++) std::swap

January 10, 2018 · View on GitHub

 

 

 

 

 

(C++) std::swap

 

Algorithm to swap two values of the same data type.

 

The definition of std::swap is in algorithm.h.

 


#include <algorithm> #include <cassert> int main() {   int a = 3;   int b = 7;   std::swap(a,b);   assert(a == 7);   assert(b == 3); }

 

Consider specializing std::swap for your own classes when you know a more efficient way to exhange their values by calling operator= three times [1].

 

 

 

 

Example definition

 


template <class T> inline void swap(T& a, T& b) {   const T tmp = a;   a = b;   b = tmp; }

 

 

 

 

 

XOR swap

 

The XOR swap is another way to swap two values. Prefer using std::swap [2].

 


void XorSwap (int *x, int *y) {   if (x != y)   {     *x ^= *y;     *y ^= *x;     *x ^= *y;   } }

 

 

 

 

 

 

 

 

 

 

 

References

 

  1. Herb Sutter. Exceptional C++ style. 2005. ISBN: 0-201-76042-8. Item 6 guideline: 'consider specializing std::swap for your own types when objects of your type have a way to exhange their values more efficiently than via brute-force assignment'.
  2. big_bad_al: How to swap two integers in C++: 'If you use the xor trick to swap integers, STOP IT!'