- // 不使用中间临时变量,交换两对象的值 ,废话少说,直接上代码
- // Virtual.cpp : 定义控制台应用程序的入口点。
- #include "stdafx.h"
- #include <iostream>
- #include <memory>
- #include <algorithm>
- #include <set>
- #include <vector>
- #include <map>
- #include <string>
- #include <cstdlib>
- using namespace std;
- // 通过函数对象来实现插入排序
- // 不用临时变量交换两个变量的值
- // 方法1
- template <typename T>
- void swap1(T& a, T& b)
- {
- a ^= b;
- b ^= a;
- a ^= b;
- }
- // 方法2
- template <typename T>
- void swap2(T& a, T& b)
- {
- a = a + b;
- b = a - b;
- a = a - b;
- }
- /*实现<的函数对象*/
- template <typename T>
- class LessThan
- {
- public:
- bool operator()(const T& left, const T& right)
- {
- return left < right;
- }
- };
- /*实现>的函数对象*/
- template <typename T>
- class GreaterThan
- {
- public:
- bool operator()(const T& left, const T& right)
- {
- return left > right;
- }
- };
- /*插入排序*/
- template <typename T, typename Compare>
- void insertSort(vector<T>& v, Compare cmp)
- {
- int size = v.size();
- for (int i=1; i<size; i++)
- {
- int temp = v[i];
- while(i>0 && cmp(temp, v[i-1]))
- {
- v[i] = v[i-1];
- i--;
- }
- v[i] = temp;
- }
- }
- int main()
- {
- vector<int> vec;
- for (int i=0; i<10; ++i)
- {
- vec.push_back(rand()%100);
- }
- printf("排序前:/n");
- copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));
- printf("/n升序排列为:/n");
- LessThan<int> less;
- insertSort(vec, less);
- copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));
- printf("/n降序排列为:/n");
- GreaterThan<int> great;
- insertSort(vec, great);
- copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));
- printf("/n");
- int a = 3;
- int b = 2;
- printf("交换前a=%d b=%d/n", a, b);
- swap1(a, b);
- printf("交换后a=%d b=%d/n", a, b);
- a = 5;
- b = 6;
- printf("交换前a=%d b=%d/n", a, b);
- swap2(a, b);
- printf("交换后a=%d b=%d/n", a, b);
- }
C++ 不用临时变量交换两个变量的值——函数对象
最新推荐文章于 2023-07-16 19:59:30 发布