[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppSwap

(C++) std::swap

Used for swapping two variables. Can be found in the STL header file algorithm.h.

Example:

  1. include <cassert>
int main() { int a = 10; int b = 20; swap(a,b); assert(a==20 && b==10); }


Below is the code I retrieved from the header file algorithm.

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


XOR swap

A less common way of swapping two integer values. Note that it does not require a temporary variable; however, in practice it can be slower than simply assigning, as the compiler can use a CPU register for the temporary rather than actual memory.

void xorSwap (int &x, int &y)
{
  x ^= y;
  y ^= x;
  x ^= y;
}


'swap' links

Code links



last edited (July 11, 2008) by bdonlan, Number of views: 3287, Current Rev: 7 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.