标准库预先定义了许多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");
}