函数对象 理解

函数对象理解:
  • C++中,只要实现了operator()的类或者结构体,都可以称为函数对象
struct SortUser {
		bool operator()(const CoreUser& u1, const CoreUser& u2) {
			return u1.cost < u2.cost;
			}
};
class find_billion{
	private:
		char country[20];
		int agebegin, ageend;
	public:
		find_billion(const char *_country, int _agebegin, int _ageend){
			strcpy(country, _country);
			agebegin = _agebegin;
			ageend = _ageend;
		}
		void operator() (const billion * tbin){
			if(strcmp(tbin->country,this->country))
				return;
			if(tbin->age < agebegin || tbin->age > ageend)
				return;
			cout<<setw(5)<<tbin -> no;
	        cout<<setw(20)<<tbin -> name;
	        cout<<setw(20)<<tbin -> account;
	        cout<<setw(2)<<tbin -> age;
	        cout<<setw(20)<<tbin -> company;
	        cout<<setw(20)<<tbin -> country;
		}
};

通过对 ( )的运算符重载来实现对函数的调用

  • 实例化

std::for_each()
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function fn)
{
while (first!=last) {
fn (*first);
++first;
}
return fn; // or, since C++11: return move(fn);
}
std::sort()与之类似

//select one:
SortUser sortuser;
sort(v.begin(), v.end(),sortuser);
//select two:
sort(v.begin(), v.end(),SortUser());

以上两种方法都可用,
select1、很显然实例化一个结构体对象sortuser,sortuser进入sort(),会执行sort()函数里的fn(*first,*first+1)即sortuser(*v.begin(),*v.begin+1),sortuser()的()为结构体SortUser中的operator().
select2、SortUser()为构造函数,SortUser()会实现实例化一个函数对象,之后就相当于sortuser了。

	for_each(bin.begin(), bin.end(), find_billion("China", 38, 45));

.为了方便理解,便设了一个find_billion()的构造函数.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值