C++ 不用临时变量交换两个变量的值——函数对象

  1. // 不使用中间临时变量,交换两对象的值 ,废话少说,直接上代码
  2. // Virtual.cpp : 定义控制台应用程序的入口点。  
  3. #include "stdafx.h"  
  4. #include <iostream>  
  5. #include <memory>  
  6. #include <algorithm>  
  7. #include <set>  
  8. #include <vector>  
  9. #include <map>  
  10. #include <string>  
  11. #include <cstdlib>  
  12. using namespace std;  
  13. // 通过函数对象来实现插入排序 
  14. // 不用临时变量交换两个变量的值
  15. // 方法1  
  16. template <typename T>  
  17. void swap1(T& a, T& b)  
  18. {  
  19.     a ^= b;  
  20.     b ^= a;  
  21.     a ^= b;  
  22. }  
  23. // 方法2  
  24. template <typename T>  
  25. void swap2(T& a, T& b)  
  26. {  
  27.     a = a + b;  
  28.     b = a - b;  
  29.     a = a - b;  
  30. }  
  31.   
  32. /*实现<的函数对象*/  
  33. template <typename T>  
  34. class LessThan  
  35. {  
  36. public:  
  37.     bool operator()(const T& left, const T& right)  
  38.     {  
  39.         return left < right;  
  40.     }  
  41. };  
  42. /*实现>的函数对象*/  
  43. template <typename T>  
  44. class GreaterThan  
  45. {  
  46. public:  
  47.     bool operator()(const T& left, const T& right)  
  48.     {  
  49.         return left > right;  
  50.     }  
  51. };  
  52. /*插入排序*/  
  53. template <typename T, typename Compare>  
  54. void insertSort(vector<T>& v, Compare cmp)  
  55. {  
  56.     int size = v.size();  
  57.     for (int i=1; i<size; i++)  
  58.     {  
  59.         int temp = v[i];  
  60.         while(i>0 && cmp(temp, v[i-1]))  
  61.         {  
  62.             v[i] = v[i-1];  
  63.             i--;  
  64.         }  
  65.         v[i] = temp;  
  66.     }  
  67. }  
  68. int main()  
  69. {  
  70.     vector<int> vec;  
  71.     for (int i=0; i<10; ++i)  
  72.     {  
  73.         vec.push_back(rand()%100);  
  74.     }  
  75.     printf("排序前:/n");  
  76.     copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));  
  77.       
  78.     printf("/n升序排列为:/n");  
  79.     LessThan<int> less;  
  80.     insertSort(vec, less);  
  81.     copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));  
  82.     printf("/n降序排列为:/n");  
  83.     GreaterThan<int> great;  
  84.     insertSort(vec, great);  
  85.     copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));  
  86.     printf("/n");  
  87.     int a = 3;  
  88.     int b = 2;  
  89.     printf("交换前a=%d b=%d/n", a, b);  
  90.     swap1(a, b);  
  91.     printf("交换后a=%d b=%d/n", a, b);  
  92.     a = 5;  
  93.     b = 6;  
  94.     printf("交换前a=%d b=%d/n", a, b);  
  95.     swap2(a, b);  
  96.     printf("交换后a=%d b=%d/n", a, b);  
  97. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值