STL仿函数简单总结

C++相对于C语言来说,有两个重点,1.面向对象特性;2.函数模板/泛型编程。对于STL中的6大组件:容器/算法/迭代器/仿函数/适配器/空间配置器。仿函数的用法比较多样化,下面简单总结一下。
使用:

    _OutIt copy_if(_InIt _First, _InIt _Last, _OutIt _Dest,
        _Pr _Pred)

这里_Pr,用于限定copy的条件。如果不符合要求的函数规范,则忽略,进行全copy。

  1. 使用1元普通函数
//1.使用1元函数
bool copyfunc1Param(const int& srcValue)
{
    return srcValue > 1;
}
  1. 使用1元仿函数
//2.使用1元仿函数
class CopyClass1Param :public unary_function<int, bool>
{
public:
    bool operator()(const int value) const
    {
        return value>2;
    }
};
  1. 使用2元普通函数,但通过特殊函数进行转换
//3.使用2元函数,直接将筛选条件传递给函数
bool copyUpNum( int srcValue,int base )
{
    return srcValue > base;
}
  1. 使用2元仿函数,进行函数因子绑定(将2元因子转化为1元因子)

//4.使用2元仿函数
class CopyClassUpNum : public binary_function<int, int, bool>
{
public:
    bool operator()(const int srcValue, const int base) const
    {
        return srcValue > base;
    }
};

测试用例如下:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<functional>
using namespace std;
int main()
{

    vector<int> srcVec;
    srcVec.push_back(2);
    srcVec.push_back(1);
    srcVec.push_back(3);
    printIntVector(srcVec);

    vector<int> targetVec;
    targetVec.resize(srcVec.size());
    //通过copy_if研究仿函数的各种用法(这里仿函数用于选择copy的条件)
    //copy_if(srcVec.begin(), srcVec.end(), targetVec.begin(), copyfunc1Param);
    //py_if(srcVec.begin(), srcVec.end(), targetVec.begin(), CopyClass1Param());

    //使用bind2nd将传递的copy标准,绑定到调用的仿函数的2nd个参数上, ptr_fun 将普通函数转化为仿函数
    //copy_if(srcVec.begin(), srcVec.end(), targetVec.begin(), bind2nd(ptr_fun(copyUpNum),1));
    copy_if(srcVec.begin(), srcVec.end(), targetVec.begin(), bind2nd(CopyClassUpNum(), 2));

    printIntVector(targetVec);




    system("pause");
    return EXIT_SUCCESS;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值