vs用户登录注册网站建设代码软文推广营销服务平台
目录
函数对象:
谓词:
一元谓词函数举例如下
二元谓词举例如下
函数对象和函数的区别
一元谓词的案例
二元函数对象案例
二元谓词案例
函数对象:
重载函数调用操作符的类,其对象常称为函数对象(function object),即它们是行为类似函数的对象。一个类对象,表现出一个函数的特征,就是通过“对象名+(参数列表)”的方式使用一个类对象,如果没有上下文,完全可以把它看作一个函数对待。
这是通过重载类的operator()来实现的。
“在标准库中,函数对象被广泛地使用以获得弹性”,标准库中的很多算法都可以使用函数对象或者函数来作为自定的回调行为;
谓词:
一元函数对象:函数参数1个;
二元函数对象:函数参数2个;
一元谓词 函数参数1个,函数返回值是bool类型,可以作为一个判断式
谓词可以使一个仿函数,也可以是一个回调函数。
二元谓词 函数参数2个,函数返回值是bool类型。
一元谓词函数举例如下
1,判断给出的string对象的长度是否小于6
bool GT6(const string &s)
{
return s.size() >= 6;
}
2,判断给出的int是否在3到8之间
bool Compare( int i )
{
return ( i >= 3 && i <= 8 );
}
二元谓词举例如下
1,比较两个string对象,返回一个bool值,指出第一个string是否比第二个短
bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
函数对象和函数的区别
//函数对象是属于类对象,能突破函数的概念,能保持调用状态信息
//函数对象的好处
//for_each算法中,函数对象做函数参数
//for_each算法中,函数对象当返回值
void main02()
{vector<int> v1;v1.push_back(1);v1.push_back(3);v1.push_back(5);for_each(v1.begin(), v1.end(), ShowElemt<int>());//匿名仿函数对象cout << endl;for_each(v1.begin(), v1.end(), FuncShowElemt2);//通过回调函数ShowElemt<int> show1;//for_each算法的函数对象的传递是元素值传递,不是引用传递for_each(v1.begin(), v1.end(), show1);show1.printN();cout << "通过for_each算法的返回值看调用的次数" << endl;show1 = for_each(v1.begin(), v1.end(), show1);show1.printN();
}
通过这个案例我们可以发现函数对象和函数最大的区别是函数对象可以记录函数的状态,普通函数需要记录值的时候只能使用全局变量的方式来实现,破坏了程序的封装性。
一元谓词的案例
template<typename T>
class IsDiv
{
public:IsDiv(const T& divisor){this->divisor = divisor;}bool operator()(T &t){return (t % divisor == 0);}
private:T divisor;
};void main03()
{vector<int> v2;for (int i = 10; i < 33; i++){v2.push_back(i);}int a = 4;IsDiv<int> myDiv(a);vector<int>::iterator iter = find_if(v2.begin(), v2.end(), myDiv);if (iter == v2.end()){cout << "容器中没有元素是4的倍数" << endl;}else{cout << "第一个被4整除的元素是:" << *iter << endl;}}
二元函数对象案例
//二元函数对象
template <typename T>
class SumAdd
{
public:T operator()(T t1, T t2){return t1 + t2;}
};//二元函数对象
void main04()
{//v1 v2==>v3vector<int> v1, v2;vector<int> v3;v1.push_back(1);v1.push_back(3);v1.push_back(5);v2.push_back(2);v2.push_back(4);v2.push_back(6);v3.resize(10);transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), SumAdd<int>());for (vector<int>::iterator it = v3.begin(); it != v3.end(); it++){cout << *it << endl;}
}
二元谓词案例
bool MyCompare(const int& a, const int& b)
{return a < b; //从小到大
}//二元谓词
void main05()
{vector<int> v1(10);for (int i = 0; i < 10; i++){int tmp = rand() % 100;v1[i] = tmp;}for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++){cout << *it << " ";}cout << endl;//遍历for_each(v1.begin(), v1.end(), FuncShowElemt2);cout << endl;sort(v1.begin(), v1.end(), MyCompare);for_each(v1.begin(), v1.end(), FuncShowElemt2);cout << endl;}