摘要:本文主要向大家介绍了 C/C++知识点之C++STL 预定义函数对象和函数适配器,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
本文主要向大家介绍了 C/C++知识点之C++STL 预定义函数对象和函数适配器,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
预定义函数对象和函数适配器
预定义函数对象基本概念:标准模板库STL提前定义了很多预定义函数对象,#include
1使用预定义函数对象:
void main()
{
plus
int x = 10;
int y = 20;
int z = intAdd(x, y); //等价于 x + y
cout << z << endl;
plus
string myc = stringAdd("aaa", "bbb");
cout << myc << endl;
vector
v1.push_back("bbb");
v1.push_back("aaa");
v1.push_back("ccc");
v1.push_back("zzzz");
}
算术函数对象
预定义的函数对象支持加、减、乘、除、求余和取反。调用的操作符是与type相关联的实例
加法:plus
plus
sres = stringAdd(sva1,sva2);
减法:minus
乘法:multiplies
除法divides
求余:modulus
取反:negate
negate
ires = intNegate(ires);
Ires= UnaryFunc(negate
关系函数对象
等于equal_to
equal_to
sres = stringEqual(sval1,sval2);
不等于not_equal_to
大于 greater
大于等于greater_equal
小于 less
小于等于less_equal
void main()
{
vector
v1.push_back("bbb");
v1.push_back("aaa");
v1.push_back("ccc");
v1.push_back("zzzz");
v1.push_back("ccc");
string s1 = "ccc";
//int num = count_if(v1.begin(),v1.end(), equal_to
int num = count_if(v1.begin(),v1.end(),bind2nd(equal_to
cout << num << endl;
}
逻辑函数对象
逻辑与 logical_and
logical_and
ires = intAnd(ival1,ival2);
dres=BinaryFunc( logical_and
逻辑或logical_or
逻辑非logical_not
logical_not
Ires = IntNot(ival1);
Dres=UnaryFunc( logical_not
函数适配器
常用函数函数适配器
1绑定器(binder): binder通过把二元函数对象的一个实参绑定到一个特殊的值上,将其转换成一元函数对象。C++标准库提供两种预定义的binder适配器:bind1st和bind2nd,前者把值绑定到二元函数对象的第一个实参上,后者绑定在第二个实参上。
2取反器(negator) : negator是一个将函数对象的值翻转的函数适配器。标准库提供两个预定义的ngeator适配器:not1翻转一元预定义函数对象的真值,而not2翻转二元谓词函数的真值。
常用函数适配器列表如下:
bind1st(op, value)
bind2nd(op, value)
not1(op)
not2(op)
class IsGreat
{
public:
IsGreat(int i)
{
m_num = i;
}
bool operator()(int &num)
{
if (num > m_num)
{
return true;
}
return false;
}
protected:
private:
int m_num;
};
void main()
{
vector
for (int i=0; i<5; i++)
{
v1.push_back(i+1);
}
for (vector
{
cout << *it << " " ;
}
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
// param > 2
int num3 = count_if(v1.begin(), v1.end(), bind2nd(greater
cout << "num3:" << num3 << endl;
//取模 能被2整除的数 求奇数
int num4 = count_if(v1.begin(), v1.end(), bind2nd(modulus
cout << "奇数num4:" << num4 << endl;
int num5 = count_if(v1.begin(), v1.end(), not1( bind2nd(modulus
cout << "偶数num5:" << num5 << endl;
return ;
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号