c++ 实现一个function object,运用“函数调用运算符重载”

标准库预先定义了许多function object,所谓function object乃是一种“提供有function call运算符 ‘()’ ”的class。
当编译器在编译过程总遇到函数调用,例如:

lt(val);

lt可能是函数名,可能是函数指针,也可能是一个提供了function call(函数调用)运算符的function object(函数类)。当lt是个类时,编译器会在内部将此语句转换为

lt.operator(val);

这边是自定义一个function object,lessthan()。

#include<iostream>
#include<vector>
#include<iterator>    
#include<algorithm>  //用于find_if
using namespace std;
class LessThan
{
private:
	int _val;
public:
	LessThan(int val) : _val (val) {}  //用成员初始化列表的方式申明并定义构造函数
	int comp_val() const   { return _val; }
	void comp_val(int nval){_val = nval; }

	bool operator()(int _value) const; //函数调用运算符重载
	
};

inline bool LessThan:: operator()(int _value) const { return _value < _val; }   //定义函数调用运算符() 

//计算数组中小于给定数的数字个数
int count_less_than(const vector<int> &vec, int comp)
{
	LessThan lt(comp);//定义类lt,并赋初值comp

	int count = 0;
	for (int i = 0; i < vec.size(); ++i)
	{
		if (lt(vec[i]))   //lt(vec[i])就等于调用了lt.operator(vec[i]),将vec[i]与comp相比
			++count;
	}
	return count;
}

//打印这些数,用find_if函数
void print_less_than(const vector<int> &vec, int comp)
{
	LessThan lt(comp);

	vector<int>::const_iterator  iter = vec.begin();
	vector<int>::const_iterator  it_end = vec.end();

	cout << "The elements less than " << lt.comp_val() << endl;
	while ((iter = find_if(iter, it_end, lt)) != it_end)
	{
		cout << *iter << ' ';
		++iter;
	}
}

int main()
{
	//int ia[16] = { 17, 12, 44, 3, 23, 9, 12, 10, 22, 11,
		//90, 24, 65, 3, 4, 8 };
	vector<int> vec;
	cout << "please enter the number to make up the vector: "<<endl;
	int num;
	while (cin >> num)
		vec.push_back(num);

	int comp_val = 20;
	cout << "Number of elements less than " << comp_val << " are " << count_less_than(vec, comp_val) << endl;

	print_less_than(vec, comp_val);

	system("pause");
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值