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;
}

猜你喜欢

转载自blog.csdn.net/guchuanhang/article/details/70940906
今日推荐