STL仿函数简单总结
来源:互联网 发布:淘宝网联盟 编辑:程序博客网 时间:2024/06/11 16:20
C++相对于C语言来说,有两个重点,1.面向对象特性;2.函数模板/泛型编程。对于STL中的6大组件:容器/算法/迭代器/仿函数/适配器/空间配置器。仿函数的用法比较多样化,下面简单总结一下。
使用:
_OutIt copy_if(_InIt _First, _InIt _Last, _OutIt _Dest, _Pr _Pred)
这里_Pr,用于限定copy的条件。如果不符合要求的函数规范,则忽略,进行全copy。
- 使用1元普通函数
//1.使用1元函数bool copyfunc1Param(const int& srcValue){ return srcValue > 1;}
- 使用1元仿函数
//2.使用1元仿函数class CopyClass1Param :public unary_function<int, bool>{public: bool operator()(const int value) const { return value>2; }};
- 使用2元普通函数,但通过特殊函数进行转换
//3.使用2元函数,直接将筛选条件传递给函数bool copyUpNum( int srcValue,int base ){ return srcValue > base;}
- 使用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
- STL仿函数简单总结
- STL源代码剖析个人总结5--STL仿函数
- C++的STL之仿函数简单介绍
- STL仿函数
- 【STL】仿函数细节
- STL仿函数
- STL仿函数functor
- c++ STL仿函数
- stl--仿函数
- stl仿函数
- stl--仿函数
- c++ STL仿函数
- stl仿函数
- 【STL】仿函数
- STL中的仿函数
- STL中的仿函数
- STL之仿函数
- C++STL:仿函数
- RecyclerView自定义分割线
- poj3130 How I Mathematician Wonder What You Are!【半平面交】
- 正向代理与反向代理的区别【Nginx读书笔记】
- 初探airflow
- java json使用以及js json
- STL仿函数简单总结
- [后缀数组] BZOJ 2119 股市的预测
- 单播,组播(多播),广播以及任播
- 《Cracking the Coding Interview程序员面试金典》----链表中倒数第k个结点
- [BZOJ4403][Lucas定理]序列统计
- tensorflow:Couldn't open CUDA library libcupti.so.8.0. LD_LIBRA
- 数据结构 二叉树实现
- 移动端界面标注:如何理清标注的思路?
- 设计模式一之单例模式