函数适配器的理论知识
STL中已经定义了大量的函数对象,
但是有时候需要对函数返回值进行进一步的简单计算,
或者填上多余的参数不能直接代入算法函数适配器实现了这一功能,
将一种函数对象转化为另一种符合要求的函数对象
函数适配器可以分为四大类,绑定适配器,组合适配器,指针函数适配器,和成员函数适配器
常用函数适配器标准库提供一组函数适配器,用来特殊化或者扩展一元和二元函数对象,常用适配器是绑定器和取反器
绑定器:通过把二元函数对象的一个实参绑定到一个特殊的纸上,将其转化成一元函数对象
取反器:是一个将函数对象的值翻转的函数适配器.
#include
using namespace std;
#include"vector"
#include"map"
#include"string"
#include"list"
#include"set"
#include"functional"
//plus 预定义好的函数对象,能实现不同类型的数据+运算
//实现了数据类型和算法的分离===>通过函数对象技术实现
void main11()
{
plus intAdd;
int x = 10;
int y = 20;
int z = intAdd(x, y);
cout << "z:" << z << endl;
plus stringAdd;
string s1 = "aaa";
string s2 = "bbb";
string s3 = stringAdd(s1,s2);
cout << "s3:" << s3 << endl;
vector v1;
v1.push_back("bbb");
v1.push_back("aaa");
v1.push_back("ccc");
v1.push_back("zzz");
sort(v1.begin(), v1.end(), greater ());
for (vector::iterator it = v1.begin(); it != v1.end(); it++);//用迭代器的方式打印出来
{
cout << *it << endl;
}
//求ccc出现的个数
string sc = "ccc";
//equal_to 有二个参数left参数来自容器,right参数来自sc
//bind2nd函数适配器,把预定义函数和第二个参数进行绑定
int num = count_if(v1.begin(), v1.end(), bind2nd(equal_to(),sc);
cout << "num" << num << endl;
}
class IsGreat
{
public:
IsGreat(int i);
{
m_num = i;
}
bool operator()(int &num)
{
if (num > m + num)
{
return ture;
}
else
{
return false;
}
}
private:
int num;
};
void main22()
{
vector v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i + 1);
}
for (vector::iterator it = v1.begin(); it != v1.end(); it++);//用迭代器的方式打印出来
{
cout << *it << endl;
}
int num1 = count(v1.begin(), v1.end(), 3);
cout << "num1" << num1 << endl;
//通过谓词 求大于2的个数
int num2 = count_if(v1.begin(), v1.end(), IsGreat);
cout << "num2" << num2 << endl;
//通过预定义的函数对象求大于2的个数
//greater()有2个参数 左参数来自容器的元素,右参数固定成2(通过bind2nd做的)
int num3 = count_if(v1.begin(), v1.end(), bind2nd(greater(),2));
cout << "num3" << num3 << endl;
//求奇数的个数
int num4 = count_if(v1.begin(), v1.end(), bind2nd(modulus(), 2));
cout << "num4" << num4 << endl;
//求偶数的个数
int num4 = count_if(v1.begin(), v1.end(), bind2nd(modulus(), 2));
cout << "num5" << num5 << endl;
}
void main()
{
main11();
//main22();
cout << "hello..." << endl;
system("pause");
return;
}
页面更新:2024-04-27
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号