#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class Cmp{
public:
bool operator()(int a,int b)const{
return a > b;
}
};
int main()
{
int a[] = {1, 2, 29, 12, 23, 10, 21};
Cmp cmp;
sort(a, a + 7, cmp);
copy(a, a + 7, ostream_iterator<int>(cout," "));
return 0;
}
仿函数的优点在于资源的整合。假设有两列数组a,b, 要根据a的元素来对b进行排序。
int fo{
int a[10];
int b[10];
sort(b, b + 10, cmp);
}
bool cmp(int n1, int n2){
return n1 > n2;
}
这时如果定义一个传统的cmp函数,就会出现问题。因为a跟b是fo函数的局部变量,如果使用传统的cmp函数,则cmp函数看不到数组b。我试过两种解决方法,一种是将数组b声明为全局变量; 一种是将a[i]与b[i]定义成pair,再将cmp函数定义成:
bool cmp(pair<int, int> n1, pair<int, int> n2){
return n1->second > n2->second;
}
第一种方法破坏了数据的封装;我之前一直使用第二种方法,但是比较麻烦,牵扯到大量pair对象的生成与销毁。用仿函数就可以解决这个问题。例如:class Cmp{
int* a;
public:
cmp(int* a) : a(a){}
bool operator()(int n1, int n2) const{
return a[n1] > a[n2];
}
}
int fo{
int a[10];
int b[10];
Cmp cmp(a);
sort(b, b + 10, cmp);
}
这样只需要一个仿函数就可以解决问题。