利用仿函数和泛型编程完成自定义数据的排序
template<class T=vector<PAIR>,class K>
void mysort(T & num,const K &cmp)
{
int size = num.size();
for (int i = 0; i <= size-2; i++)
{
for (int j = 0; j < size - i - 1; j++)
{
if (cmp(num[j],num[j+1]))
swap(num[j], num[j + 1]);
}
}
}
借鉴stl的sort(C++98版本)
给mysort的判断条件提供仿函数接口(仿函数在C++中优化,速度和函数指针一样,避免命名污染,直接封装)
本例中,我们提供fun_cmp对象 利用重载operator()来传入自定义比较方式。
例如,我想对pair二元组进行排序,要求升序且在first相等情况下,以second为主。
int flag=0;
#define PAIR pair<int,int>
template<class T=PAIR>
struct fun_cmp {
bool operator()(const T a, const T b)const
{
bool ret = a.first > b.first || (a.first == b.first && a.seco