仿函数
来源:互联网 发布:如何做好网络直销 编辑:程序博客网 时间:2024/04/29 08:41
#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);
}
这样只需要一个仿函数就可以解决问题。
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- iFix调用外部置顶窗体执行文件
- OpenGL中光照的设置
- create table like 和create table select 比较
- 微软安全新闻聚焦-双周刊第二十六期
- 抑止TDD noise
- 仿函数
- 纯html+js+xml 导航功能
- 正则表达式快速入门
- MVC 3 学习笔记及小技巧
- 南京师范大学2012年GIS考研试题
- A Quick Look at CMMI-SVC
- JavaScript
- 权限管理 ,不错的,国人写的。
- awk 统计访问时间超过1000毫秒的接口