C/C++ 交换两个数,不使用第三个变量, 函数模板来实现
生活随笔
收集整理的這篇文章主要介紹了
C/C++ 交换两个数,不使用第三个变量, 函数模板来实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <iostream>template<typename T>
void exchangeTwoNumber(T &t1, T &t2);
void test();int main() {int a = 10, b = 20;double q = 10.1, w = 20.2;char z = 'z', x = 'x';std::cout << "交換前的 a = " << a << ", b = " << b << std::endl;std::cout << "交換前的 q = " << q << ", w = " << w << std::endl;std::cout << "交換前的 z = " << z << ", x = " << x << std::endl;exchangeTwoNumber(a, b);exchangeTwoNumber(q, w);exchangeTwoNumber(z, x);test();std::cout << std::endl;std::cout << std::endl;std::cout << "交換后的 a = " << a << ", b = " << b << std::endl;std::cout << "交換后的 q = " << q << ", w = " << w << std::endl;std::cout << "交換后的 z = " << z << ", z = " << x << std::endl; }template<typename T> void exchangeTwoNumber(T &t1, T &t2) //通用的函數模板 {t1 = t1 + t2;t2 = t1 - t2;t1 = t1 - t2; }void test() //異或的方式,變形成函數模板,編譯不通過 {int a = 1, b = 2;a ^= b;b ^= a;a ^= b;std::cout << "...a=" << a << ", b=" << b << std::endl; }
void test();int main() {int a = 10, b = 20;double q = 10.1, w = 20.2;char z = 'z', x = 'x';std::cout << "交換前的 a = " << a << ", b = " << b << std::endl;std::cout << "交換前的 q = " << q << ", w = " << w << std::endl;std::cout << "交換前的 z = " << z << ", x = " << x << std::endl;exchangeTwoNumber(a, b);exchangeTwoNumber(q, w);exchangeTwoNumber(z, x);test();std::cout << std::endl;std::cout << std::endl;std::cout << "交換后的 a = " << a << ", b = " << b << std::endl;std::cout << "交換后的 q = " << q << ", w = " << w << std::endl;std::cout << "交換后的 z = " << z << ", z = " << x << std::endl; }template<typename T> void exchangeTwoNumber(T &t1, T &t2) //通用的函數模板 {t1 = t1 + t2;t2 = t1 - t2;t1 = t1 - t2; }void test() //異或的方式,變形成函數模板,編譯不通過 {int a = 1, b = 2;a ^= b;b ^= a;a ^= b;std::cout << "...a=" << a << ", b=" << b << std::endl; }
?
轉載于:https://www.cnblogs.com/azbane/p/11261698.html
總結
以上是生活随笔為你收集整理的C/C++ 交换两个数,不使用第三个变量, 函数模板来实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Diamond/Quartus 工具的b
- 下一篇: 准备试用svn