MDGSF Software Engineer

[C/C++] Swap函数实现

2016-04-08
mdgsf
   

#include <stdio.h>
#include <iostream>
using namespace std;

void Swap1(int & a, int & b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

void Swap2(int * pa, int * pb)
{
    int tmp = *pa;
    *pa = *pb;
    *pb = tmp;
}

//不过这样写存在一个隐患,如果a, b指向的是同一个数或两个相等的数,那么调用Swap3()函数会使这个数为0。
//所以要加上判断 if(a!=b) 的时候才执行。
void Swap3(int & a, int & b)
{
    if(a != b)
    {
        a ^= b;
        b ^= a;
        a ^= b;
    }
}

void Swap4(int & a, int & b)
{
    a = a + b;
    b = a - b;
    a = a - b;
}

int main()
{
    int a = 3;
    int b = 8;

    a = 3;
    b = 8;
    printf("a=%d, b=%d\n", a, b);
    swap(a, b); //使用c++的库函数
    printf("a=%d, b=%d\n\n", a, b);

    a = 3;
    b = 8;
    printf("a=%d, b=%d\n", a, b);
    Swap1(a, b);
    printf("a=%d, b=%d\n\n", a, b);

    a = 3;
    b = 8;
    printf("a=%d, b=%d\n", a, b);
    Swap2(&a, &b);
    printf("a=%d, b=%d\n\n", a, b);

    a = 3;
    b = 8;
    printf("a=%d, b=%d\n", a, b);
    Swap3(a, b);
    printf("a=%d, b=%d\n\n", a, b);
    return 0;
}

weixingongzhonghao

Similar Posts

Comments