生活随笔
收集整理的這篇文章主要介紹了
swap交换算法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
交換算法(swap)
- void swap(int x,int y)
- void swap(int *px,int *py)
- #define swap(x,y,t) ?((t)=(x),(x)=(y),(y)=(x))
- void swap(int &x,int &y)
- template<class T> void swap(T&x,T&y)
#include<iostream>
using namespace std;
void swap(int &x, int &y);
int main()
{int a = 1;int b = 10;//C++ 引用實(shí)現(xiàn)swap(a, b);cout << "a=" << a << "," << "b=" << b << endl;//C++ 現(xiàn)成的模板類std::swap(a, b);cout << "a=" << a << "," << "b=" << b << endl;system("pause");return 0;
}//C++ 引用方式實(shí)現(xiàn)
void swap(int &x, int &y)
{int tmp;tmp = x;x = y;y = tmp;
}
#include<stdio.h>
void swap(int *x, int *y);
#define SWAP(x,y,t) ((t)=(x),(x)=(y),(y)=(t))//注意括號(hào)的使用
int main()
{int a = 1;int b = 10;int t;//C 指針實(shí)現(xiàn)swap(&a, &b);printf("a=%d,b=%d\n", a, b);//宏定義實(shí)現(xiàn)SWAP(a, b,t);printf("a=%d,b=%d\n", a, b);getchar();return 0;
}
在這四種實(shí)現(xiàn)方式中,需要注意每種實(shí)現(xiàn)方式的異同,以及如何調(diào)用。
總結(jié)
以上是生活随笔為你收集整理的swap交换算法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。