最近学的时候碰到一个东西叫函数适配器。越学C++,越觉得它牛逼啊。
总结一下。
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
/*
函数适配器:
STL中已经定义了大量的函数对象,但是有时候需要对函数返回值进行进一步的简单计算,
或者填上多余的参数,不能直接代入算法,函数适配器实现了这一功能,将一种函数对象
转化为另一种符合要求的函数对象。函数适配器可以分为4大类:绑定适配器,组合适配器,
指针函数适配器和成员函数适配器
*/
/*
绑定器(binder):binder通过把二元函数对象的一个实参绑定到一个特殊的值上,
将其转换成一元函数对象。C++标准库提供两种预定义的binder适配器,bind1st
和bind2nd,前者把值绑定到二元函数对象的第一个实参上,后者绑定到第二个实参上。
取反器(negator):negator是一个将函数对象的值翻转的函数适配器。标准库提供两个
预定义的negator适配器,not1翻转一元预定义函数对象的真值,而not2翻转二元谓词函数的真值
*/
struct IsGreat
{
IsGreat(int i)
{
n_num = i;
}
bool operator()(int &num)
{
if (num > n_num)
{
return true;
}
return false;
}
private:
int n_num;
};
void test()
{
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 << "num1: " << num1 << endl;
//通过谓词求大于2的个数
int num2 = count_if(v1.begin(), v1.end(), IsGreat(2));
cout << "num2: " << num2 << endl;
//通过预定义的函数对象 求大于2 的个数
//greater<int>() 有两个参数 左参数来自容器的元素 右参数固定成2(通过bind2nd来固定)
int num3 = count_if(v1.begin(), v1.end(), bind2nd(greater<int>(), 2));
cout << "num3: " << num3 << endl;
//求奇数的个数
int num4 = count_if(v1.begin(), v1.end(), bind2nd(modulus<int>(), 2));
cout << "奇数的个数: " << num4 << endl;
//求偶数的个数
int num5 = count_if(v1.begin(), v1.end(), not1(bind2nd(modulus<int>(), 2)));
cout << "偶数的个数:" << num5 << endl;
}
int main()
{
test();
getchar();
getchar();
return 0;
}