版权声明:瞎几把写 https://blog.csdn.net/weixin_43184615/article/details/82961489
标准库预先定义了许多function object,所谓function object是某种class的实例对象。
functional头文件里自带的六个关系运算:less, less_equal, greater, greater_equal, equal_to, not_equal_to.
搭配bind2nd()函数使用,bind2nd(less(),val),将val绑定到less() function object的第二个参数,作为比较的基准数。
这边是自定义一个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);
int count = 0;
for (int i = 0; i < vec.size(); ++i)
{
if (lt(vec[i]))
++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");
}