博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ Primer Plus 学习笔记 第十六章 函数符
阅读量:4127 次
发布时间:2019-05-25

本文共 2532 字,大约阅读时间需要 8 分钟。

啥是函数符

有定义了operator()()的类

函数符概念

这些都是概念 就是一个称呼 

程序示例

#include 
#include
#include
// STL的算法库#include
template
class TooBig{ private: T cutoff; public: TooBig(const T & t) : cutoff(t) {}// 定义了operator()() bool operator()(const T & v) {return v > cutoff;}};void outint(int n) {std::cout << n << " ";}int main(){ using std::list; using std::cout; using std::endl; TooBig
f100(100); int vals[10] = {50, 100, 90, 180, 60, 210, 415, 88, 188, 201}; list
yadayada(vals, vals + 10); list
etcetera(vals, vals + 10); cout << "Original lists:\n"; for_each(yadayada.begin(), yadayada.end(), outint); cout << endl; for_each(etcetera.begin(), etcetera.end(), outint); cout << endl;// list容器的内置函数 remove_if() 会将容器中的每个元素丢给f100 将f100这个类对象当做函数来调用(类名后面加括号 )这样就调用了operator()函数 返回true的话 就删除元素 yadayada.remove_if(f100); etcetera.remove_if(TooBig
(200)); cout << "Trimmed lists:\n"; for_each(yadayada.begin(), yadayada.end(), outint); cout << endl; for_each(etcetera.begin(), etcetera.end(), outint); cout << endl; return 0;}

运行结果

函数适配器

预定义的函数符

就是C++ 内置的函数符

在<functional>中

C++ 针对内置的算术运算符、关系运算符和逻辑运算符 都提供了预定义的函数符

自适应函数符

自适应生成器,自适应一元函数,自适应二元函数,自适应谓词, 自适应二院谓词

自适应函数符中有标识参数类型,返回类型的成员变量result_type, first_argument_type, second_argument_type(二元函数的第二个参数类型名称)

STL内置binder1st和binder2nd类(函数适配器)将二元函数转成一元函数

另一个适配器:

bind1st() 其实就是将binder1st做成匿名函数而已

用法:

#include 
#include
#include
#include
#include
void Show(double);const int LIM = 6;int main(){ using namespace std; double arr1[LIM] = {28, 29, 30, 35, 38, 59}; double arr2[LIM] = {63, 65, 69, 75, 80, 99}; vector
gr8(arr1, arr1 + LIM); vector
m8(arr2, arr2 + LIM); cout.setf(ios_base::fixed); cout.precision(2); cout << "gr8:\t"; for_each(gr8.begin(), gr8.end(), Show); cout <
sum(LIM); transform(gr8.begin(), gr8.end(), m8.begin(), sum.begin(), plus
()); cout << "sum:\t"; for_each(sum.begin(), sum.end(), Show); cout << endl; vector
prod(LIM); transform(gr8.begin(), gr8.end(), prod.begin(),// 这里使用了bind1st 其实就是建立了类似binder1st()的匿名函数 然后将gr8的每个元素和2.5丢给multiplies对象的operator() bind1st(multiplies
(), 2.5)); cout << "prod:\t"; for_each(prod.begin(), prod.end(), Show); cout << endl; return 0;}void Show(double v){ std::cout.width(6); std::cout << v << ' ';}

运行结果

c++11提供了lambda表达式(python的匿名函数标识符么? 不知道 18章会说到)

函数对象完结

转载地址:http://fsepi.baihongyu.com/

你可能感兴趣的文章
Agent admitted failure to sign using the key
查看>>
ubuntu解决包依赖关系
查看>>
ubuntu 安装ffmpeg1.0 , opencv2.4.2
查看>>
MyEclipse安装CDT插件
查看>>
ubuntu下eclipse集成OpenCv
查看>>
OpenCv将图片写入到视频文件中
查看>>
在csdn博客上添加qq聊天窗口插件
查看>>
launch failed.Binary not found(CDT---eclipse编写c++出现的问题)
查看>>
Qt开发的程序添加ico图标
查看>>
三系统安装win7+ubuntu+win8以及出现的问题
查看>>
Win8双系统下硬盘某分区无法访问的解决方案
查看>>
CSDN全国巡讲---重庆大学站
查看>>
SQLITE 修改表结构
查看>>
ubuntu支持中文输入
查看>>
mtd命令及制作ubi镜像做根文件系统
查看>>
lighttpd+php(fastcgi) 移植到arm-linux
查看>>
lighttp+php+arm-ubuntu上传文件(带滚动条)
查看>>
三大WEB服务器对比分析(apache ,lighttpd,nginx)
查看>>
HTTP协议详解
查看>>
关于linux的tcp/udp缓存
查看>>