#include <iostream> //标准输入输出流
using namespace std;//标准命名空间
const int CMP_LES = -1;//定义的常量
const int CMP_EQU = 0;
const int CMP_BIG = 1;
class Comparer //仿函数的类 函数的主要功能是重载运算符()这样调用的时候就直接用类引用加上()后面的参数就可以
{
public:
Comparer(int cmpType)
{
m_cmpType = cmpType;//初始化变量
}
bool operator ()(int num1, int num2) const
{
bool res;
switch(m_cmpType)
{
case CMP_LES:
res = num1 < num2;
break;
case CMP_EQU:
res = num1 == num2;
break;
case CMP_BIG:
res = num1 > num2;
break;
default:
res = false;
break;
}
return res;
}
private:
int m_cmpType;
};
//互相交换数值
void Swap(int &num1, int &num2)
{
int temp = num1;
num1 = num2;
num2 = temp;
}
//这个是个排序函数 双层循环来排列顺序
void SortArray(int array[], int size, const Comparer &cmp)
{
for (int i = 0; i < size - 1; ++i)
{
int indx = i;
for (int j = i + 1; j < size; ++j)
{
if (cmp(array[indx], array[j]))//这里是对仿函数类的引用 看看很像函数
{
indx = j;
}
if (indx != i)
{
Swap(array[i], array[indx]);
indx = i; //这句必须尤其要注意,千万不能忘了
}
}
}
}
//这是输出显示函数
void ListArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
{
cout << array[i] << " ";
}
}
#define ARY_SIZE 10
int main()
{
int array[ARY_SIZE] = {10, 12, 9, 31, 93, 34, 98, 9, 1, 20};//定义一个数组 有十个数据
cout << "The initial array is : ";//首先输出现在的数组数据
ListArray(array, ARY_SIZE);
cout << endl;
SortArray(array, ARY_SIZE, Comparer(CMP_BIG));//然后在这里用到了SortArray排序函数 其中第三个参数是个
//对象的引用 所以要初始化这个对象(他是先初始化Comparer对象然后再动作的)
cout << "The ascending sorted array is :";
ListArray(array, ARY_SIZE);
cout << endl;
SortArray(array, ARY_SIZE, Comparer(CMP_LES));//用这个方法来排序
cout << "The descending sorted array is : ";//输出排序以后的方法
ListArray(array, ARY_SIZE);
int wait;
cin >> wait;
return 0;
}