本文主要介绍预定义函数和函数适配器。预定义好的函数对象,能实现不同类型的数据的运算, 实现了数据类型 和算法的分离===》通过函数对象技术实现。下面是示例代码:
#include "iostream"
using namespace std;
#include "vector"
#include "set"
#include "queue"
#include "list"
#include "algorithm"
#include "string"
#include "functional"
// plus<type> 预定义好的函数对象,能实现不同类型的数据的 运算
// 实现了数据类型 和算法的分离===》通过函数对象技术实现的
void main21()
{
//template<class _Ty>
//struct plus
// : public binary_function<_Ty, _Ty, _Ty>
//{ // functor for operator+
// _Ty operator()(const _Ty& _Left, const _Ty& _Right) const
// { // apply operator+ to operands
// return (_Left + _Right);
// }
//};
plus<int> intAdd;
int x = 10;
int y = 20;
int z = intAdd(x,y);// x+y
cout << "z:" << z << endl;//结果为 30
plus<string> stringAdd;
string s1 = "aaa";
string s2 = "bbb";
string s3 = stringAdd(s1,s2);
cout << "s3:" <<s3 << endl;// 结果为 aaabbb
vector<string> v1;
v1.push_back("bbb");
v1.push_back("aaa");
v1.push_back("ccc");
v1.push_back("zzz");
sort(v1.begin(),v1.end(),greater<string>());// 从大到小
for (vector<string>::iterator it=v1.begin();it!=v1.end();it++)
{
cout << *it << endl;
}
// 求 ccc 出现的个数
string sc = "ccc";
//equal_to<string>() 有两个参数,来自容器,来自sc
// bind2nd 函数适配器,把预定义函数对象 和第二个参数进行绑定
int num = count_if(v1.begin(),v1.end(),bind2nd (equal_to<string>(),sc));
cout << "num:" << num << endl;
}
class IsGreat
{
public:
IsGreat(int i)
{
m_num = i;
}
bool operator()(int &num)
{
if (num > m_num)
{
return true;
}
else
{
return false;
}
}
protected:
private:
int m_num;
};
void main22()
{
vector<int> v1;
for (int i=0;i<10;i++)
{
v1.push_back(i+1);
}
for (vector<int>::iterator it = v1.begin();it!=v1.end();it++)
{
cout << *it << " ";
}
cout << endl;
int num1 = count(v1.begin(),v1.end(),3);
cout << "=3 的 num1:"<< num1 << endl;
// 通过谓词求>2的个数
int num2 = count_if(v1.begin(),v1.end(),IsGreat(2));
cout << ">2的num2:" << num2 << endl;
// 通过预定义的函数对象求>2 的函数对象
// greater<int>()有两个参数,左参数来自容器的元素,右参数来自固定比较数2
int num3 = count_if(v1.begin(),v1.end(),bind2nd(greater<int>(),2));
cout << ">2的num3:" << num3 << endl;
// 求奇数的个数
int num4 = count_if(v1.begin(),v1.end(),bind2nd(modulus<int>(),2));
cout << "奇数的个数 num4:" << num4 << endl;
// 求偶数的个数
int num5 = count_if(v1.begin(),v1.end(),not1(bind2nd(modulus<int>(),2)));// 对上面去反
cout << "偶数的个数num5:" << num5 << endl;
}
void main()
{
//main21();
main22();// 函数适配器综合性案例
cout << "hello..."<< endl;
system("pause");
}