小言_互联网的博客

C++ a,b的比较与交换

550人阅读  评论(0)
#include<iostream>
using namespace std;

//获取两个数的最大者
int maxNum(int a, int b)
{
    return (a + b + abs(a - b)) >> 1;
}

//获取两个数的最小者
int minNum(int a, int b)
{
    return (a + b - abs(a - b)) >> 1;
}

//----------------------------------
//可以采用引用、指针、标准运算、异或、内存拷贝
//针对于整数类型可以采用 异或方式
//----------------------------------
template <typename T>
void swapByReference(T & a, T & b)
{
    T c;
    c = a;
    a = b;
    b = c;
}

template <typename T>
void swapByPointer(T * a, T * b)
{
    T c;
    c = *a;
    *a = *b;
    *b = c;
}

template <typename T>
void swapByStandard(T & a, T & b)
{
    a = a + b;
    b = a - b;
    a = a - b;
}

template <typename T>
void swapByXOR(T & a, T & b)
{
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
}

//内存拷贝可针对
int main()
{
	cout << maxNum(-1, 7) << endl;
	cout << minNum(-1, 7) << endl;

    int a = 1,b = 2;
    swapByReference(a, b); //引用,这里一定不能传成 &a, &b  否则变成取地址了
    cout << "a=" <<a<<"  "<<"b="<< b << endl;
    int c = 3, d = 4;
    swapByPointer(&c, &d);
    cout << "c=" <<c<<"  "<<"d="<< d << endl;
    swapByStandard(a, b);
    cout << "a=" <<a<<"  "<<"b="<< b << endl;
    swapByXOR(a, b);
    cout << "a=" <<a<<"  "<<"b="<< b << endl;

    double f = 1.2, g = 3.4;
    swapByReference(f, g);
    cout << "f=" <<f<<"  "<<"g="<< g << endl;

    string p = "hello", q = "word";
    swapByReference(p, q);
    cout << "p=" <<p<<"  "<<"q="<< q << endl;
	return 0;
}


转载:https://blog.csdn.net/yeler082/article/details/102092414
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场