swap

C[edit] This has a restriction that a and b must be the same size.

void swap(void *va, void *vb, size_t s)
{
  char t, *a = (char*)va, *b = (char*)vb;
  while(s--)
    t = a[s], a[s] = b[s], b[s] = t;
}
Usage examples are:

#include <stdio.h>

#define Swap(X,Y)  do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0)

struct test
{
  int a, b, c;
};


int main()
{
  struct test t = { 1, 2, 3 };
  struct test h = { 4, 5, 6 };
  double alfa = 0.45, omega = 9.98;

  struct test *pt = &t;
  struct test *th = &h;

  printf("%d %d %d\n", t.a, t.b, t.c );
  Swap(t, h);
  printf("%d %d %d\n", t.a, t.b, t.c );
  printf("%d %d %d\n", h.a, h.b, h.c );

  printf("%lf\n", alfa);
  Swap(alfa, omega);
  printf("%lf\n", alfa);

  printf("%d\n", pt->a);
  Swap(pt, th);
  printf("%d\n", pt->a);
}
This is tested with GCC with -std=c89 option.

C++

The implementation of the swap function template is straightforward:

template<typename T> void swap(T& left, T& right)
{
  T tmp(left);
  left = right;
  right = tmp;
}

Note that this function requires that the type T has an accessible copy constructor and assignment operator.

C++11

C++11 adds move constructors which can be more efficient than copy constructors.

template<class T>
void swap(T &lhs, T &rhs){
  T tmp = std::move(lhs);
  lhs = std::move(rhs);
  rhs = std::move(tmp);
}

results matching ""

    No results matching ""