经典函数之Sway函数

来源:互联网 发布:青牛软件怎么样 编辑:程序博客网 时间:2024/06/06 05:26

一.借助辅助变量实现Sway函数
1.指针类型作形参
函数实现

void swap(int *p, int *q)  {      int temp;      temp = *p;      *p = *q;      *q = temp;    } 

类模板

template <class T>void swap(T *p, T *q)  {      T temp;      temp = *p;      *p = *q;      *q = temp;    } 

2.引用类型作形参
函数实现

void swap(int &p, int &q)  {      int temp;      temp = p;      p = q;      q = temp;    } 

类模板

template <class T>void swap(T &p, T &q)  {      T temp;      temp = p;      p = q;      q = temp;    } 

了解指针和引用的区别请点击http://blog.csdn.net/dujiangyan101/article/details/2844138

二.利用加减运算实现Sway函数
1.指针类型作形参
函数实现

void swap(int *p, int *q)  {       *p+=*q;    *q=*p-*q;    *p-=*q;   } 

类模板

template <class T>void swap(T *p, T *q)  {      *p+=*q;    *q=*p-*q;    *p-=*q;   } 

2.引用类型作形参
函数实现

void swap(int &p, int &q)  {      p+=q;    q=p-q;    p-=q;    } 

类模板

template <class T>void swap(T &p, T &q)  {      p+=q;    q=p-q;    p-=q;    } 

三.利用异或运算实现Sway函数
1.指针类型作形参
函数实现

void swap(int *p, int *q)  {       *p^=*q;    *q^=*p;    *p^=*q;   } 

类模板

template <class T>void swap(T *p, T *q)  {      *p^=*q;    *q^=*p;    *p^=*q;   } 

2.引用类型作形参
函数实现

void swap(int &p, int &q)  {      p^=q;    q^=p;    p^=q;    } 

类模板

template <class T>void swap(T &p, T &q)  {      p^=q;    q^=p;    p^=q;    } 

四.利用宏定义实现Sway函数

异或

#define swap(p, q) { p ^= q; q ^= p; p ^= q; }
#define swap(*p, *q) { *p ^= q; *q ^= *p; *p ^= *q; }
#define swap(&p, &q) { p ^= q; q ^= p; p ^= q; }

加减法

#define swap(p, q) { p = p + q; q = p - q; p = p - q; }
#define swap(*p, *q) { *p = *p + *q; *q = *p - *q; *p = *p - *q; }
#define swap(&p, &q) { p = p + q; q = p - q; p = p - q; }

以上如有错误,请立即指出,我立马改正。

原创粉丝点击