2019独角兽企业重金招聘Python工程师标准>>>

The Concept of Function Objects

A function object, or functor, is an object that has operator () defined so that int the following example

FunctionObjectType fo;
//...
fo(...);

the expression fo() is a call of operator () for the function object fo instead of a call of the function fo().

So the function object define as follow:

Class X {public://define "function call" operator:return-value operator() (arguments) const;//...
};

Now you can use objects of this class to behave like a function that you can call:

X fo;
...
//call operator () for function object fo
fo(arg1, arg2);  //equivalent to: fo.operator() (arg1, ar2);

Function objects are more than functions, and they have some advantages:

  1. Function objects are "function with state". Object that behave like pointers are smart pointers.
  2. Each function object has its own type. Ordinary functions have different types only when their signatures differ. However, function objects can have different types even when their signatures are the same.
  3. Function objects are usually faster than ordinary functions.

Suppose that you want to add a certain value to all elements of a collection. If you know the value you want to add at compile time, you could use an ordinary function.

If you need different values that are known at compile time, you could use a template instead.

If you process the value to add at runtime,things get complicated. With function objects, you can write a "smater" function that behaves in the desired way. Because it may have a state, the object can be initialized by the correct value.

#include <list>
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include "print.hpp"
using namespace std;//function object that adds the value with which it is initialized
class AddValue {
private:int theValue;    //the value to addpublic://construct initializes the value toaddAddValue(int v):theValue(v){}//the "function call" for the element adds the valuevoid operator() (int& elem) const {elem += theValue;}
};int main()
{list<int> coll;//insert elements from 1 to 9for(int i=1; i <= 9; ++i) {coll.push_back(i);}PRINT_ELEMENTS(coll, "initialized:  ");//add value 10 to each elementfor_each(coll.begin(), coll.end(), AddValue(10));PRINT_ELEMENTS(coll, "after adding 10:  ");//add value of first element to each elementfor_each(coll.begin(), coll.end(), AddValue(*coll.begin()));PRINT_ELEMENTS(coll, "after adding first element:  ");system("pause");
}/** output of program:** initialized:  1 2 3 4 5 6 7 8 9* after adding 10:  11 12 13 14 15 16 17 18 19* after adding first element:  22 23 24 25 26 27 28 29 30**/

Predefined Function Objects

The C++ standard library contains several predefined function objects that cover fundamental operations. By use them, you don't have to write your own function objects in several cases. A typical example is a function onject used  as a sorting criterion.

set<int, less<int>> coll;    //sort elements with <
set<int, greater<int>> coll; //sort elements with >

Another place to apply predefined function objects are algorithms. Consider the following example:

#include <deque>
#include <algorithm>
#include <functional>
#include <iostream>
#include <cstdlib>
#include "print.hpp"
using namespace std;int main()
{deque<int> coll = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };PRINT_ELEMENTS(coll, "initialized: ");//negate all values in colltransform(coll.cbegin(), coll.cend(), coll.begin(), negate<int>());PRINT_ELEMENTS(coll, "negate: ");//square all vlaues in colltransform(coll.cbegin(), coll.cend(), coll.cbegin(), coll.begin(), multiplies<int>());PRINT_ELEMENTS(coll, "squared: ");system("pause");
}/** output of program:** initialized: 1 2 3 4 5 6 7 8 9* negate: -1 -2 -3 -4 -5 -6 -7 -8 -9* squared: 1 4 9 16 25 36 49 64 81**/// print.hpp#include<iostream>
#include<string>//PRINT_ELEMENTS()
// - prints optional string optstr followed by
// - all elements of the collection coll
// - in one line,separated by spaces
template <typename T>
inline void PRINT_ELEMENTS(const T& coll, const std::string& optstr="")
{std::cout << optstr;for(const auto& elem : coll) {std::cout << elem << ' ';}std::cout << std::endl;
}

The header for the predefined function objects is included <functional>

Then, two predefined function objects are used to negate and square the elements in coll.

Binders

You can use special function adapters, or so-called binders, to combine predefined function objects with other values or use special cases;

#include <set>
#include <deque>
#include <algorithm>
#include <iterator>
#include <functional>
#include <iostream>
#include <cstdlib>
#include "print.hpp"
using namespace std;
using namespace std::placeholders;int main()
{set<int, greater<int>> coll1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };deque<int> coll2;//Note: due to the sorting criterion greater<>() elements have reverse order;PRINT_ELEMENTS(coll1, "initialized: ");//transform all elements into coll2 by multiplying them with 10transform(coll1.cbegin(), coll1.cend(), back_inserter(coll2), bind(multiplies<int>(), _1, 10));PRINT_ELEMENTS(coll2, "transformed: ");//replace vlaue equal to 70 with 42replace_if(coll2.begin(), coll2.end(),bind(equal_to<int>(), _1, 70),42);PRINT_ELEMENTS(coll2, "replaced: ");//remove all elements with vlaues between 50 and 80coll2.erase(remove_if(coll2.begin(), coll2.end(),bind(logical_and<bool>(),bind(greater_equal<int>(), _1, 50),bind(less_equal<int>(), _1, 80))),coll2.end());PRINT_ELEMENTS(coll2, "removed: ");system("pause");
}/** output of program:** initialized: 9 8 7 6 5 4 3 2 1* transformed: 90 80 70 60 50 40 30 20 10* replaced: 90 80 42 60 50 40 30 20 10* removed: 90 42 40 30 20 10**/// print.hpp#include<iostream>
#include<string>//PRINT_ELEMENTS()
// - prints optional string optstr followed by
// - all elements of the collection coll
// - in one line,separated by spaces
template <typename T>
inline void PRINT_ELEMENTS(const T& coll, const std::string& optstr="")
{std::cout << optstr;for(const auto& elem : coll) {std::cout << elem << ' ';}std::cout << std::endl;
}

STL--Function Objects(二)    http://my.oschina.net/daowuming/blog/686879

转载于:https://my.oschina.net/daowuming/blog/685188

STL--Function Objects(一)相关推荐

  1. 仿函数(functors/function objects)原理及使用

    仿函数(functors,或名 function objects,函数对象),是 STL 六大组件(Components)的重要一环,如下图: 在STL的历史上,仿函数(functors)是早期的命名 ...

  2. 18函数对象19command模式20函数对象在STL中的应用

    Item 18. Function Objects Item 19. Commands and Hollywood Item 20. STL Function Objects 1.unction Ob ...

  3. STL源码剖析(四)

    functors 仿函数(functor),就是使一个类的使用看上去像一个函数.其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了. 在STL中,将仿函数主要分 ...

  4. STL源码剖析 hashtable

    二叉搜索树具有对数平均时间的表现,但是这个需要满足的假设前提是输入的数据需要具备随机性 hashtable 散列表这种结构在插入.删除.搜寻等操作层面上也具有常数平均时间的表现.而且不需要依赖元素的随 ...

  5. 标准模板库STL(Standard Template Library)

    标准模板库STL(Standard Template Library)指南 /*刘振飞liuzf@pku.org.cn 1999-10-20*/ / *版权所有 (C) 1999-2004 刘振飞li ...

  6. Qt框架与STL库之间的巅峰对决:差异、优缺点及适用场景

    Qt框架与STL库之间的巅峰对决:差异.优缺点及适用场景 引言 对比的重要性 Qt框架与STL库简介 博客内容概览 Qt框架基础 Qt框架的特点与组成 Qt的信号槽机制 Qt容器类简介 数据结构的对比 ...

  7. 《泛型编程与stl》

    以下是STL六大组件(componments): adapters  配接器 用来修饰其他组件.包括iterator adapters.function  adapters.container ada ...

  8. STL 标准模板库详细

    STL就是Standard Template Library,标准模板库.这可能是一个历史上最令人兴奋的工具的最无聊的术语.从根本上说,STL是一些"容器"的集合,这些" ...

  9. C++ STL 标准模板库

    STL就是Standard Template Library,标准模板库.这可能是一个历史上最令人兴奋的工具的最无聊的术语.从根本上说,STL是一些"容器"的集合,这些" ...

  10. STL学习_配接器篇

    STL学习_配接器篇 定义 配接器(Adapter)在STL组件的灵活组合运用功能上,扮演着轴承.转换器的角色.它事实上是一种设计模式.即将一个class的接口转换为另一个class的接口,使原本因接 ...

最新文章

  1. 新特效火爆抖音!各路神仙齐唱《蚂蚁呀嘿》,网友:短短几秒需一生来治愈...
  2. python绘制动态模拟图-Python 模拟生成动态产生验证码图片的方法
  3. [数据库事务与锁]详解一: 彻底理解数据库事务
  4. Codeforces Global Round 4 题解
  5. access violation at address in module Read of address
  6. 开设计算机应用基础这门学科意义,计算机应用基础与专业课程整合思考.doc
  7. 计算机网络「四」 网络层
  8. java 集合中对象的排序 和去重
  9. MinGW —— Minimalist GNU for Windows、Cygwin —— Windows 下的类 unix 系统
  10. Lc1013将数组分成相等的三个部分
  11. bootice.exe linux 启动盘,怎么用bootice自己手动制作U盘启动-支持BIOS+UEFI
  12. 附资料:工程总承包项目管理流程图(全套)
  13. 华为云数据容灾方案助力中小企业发展
  14. 百度网盘打不开的问题的解决
  15. SDN:简述对各类SDN交换机的认识
  16. 公积金贷款额度根据什么而定
  17. 小程序(十)签到业务流程分析
  18. 说话中的引题技巧,及电影刘三姐中的歌词汇总
  19. 脑机接口竞赛( BCI competition)数据集,其他数据集下载链接
  20. 入门SpringBoot-关于那些静态资源(四)

热门文章

  1. Wireshark数据包分析之数据包信息解读
  2. java8(2)函数式接口
  3. 基于zeromq的高性能分布式RPC框架Zerorpc 性能测试
  4. java中equals方法的用法以及==的用法(转)
  5. VC++六种Runtime Library
  6. Dubbo思维导图知识点整理
  7. Spring Mvc Controller返回值、参数绑定、参数校验 (高级二)
  8. ts引入公共方法_angular 封装公共方法
  9. 在Xuper链上部署Java语言智能合约和分析存证合约的实现逻辑
  10. php xdebug 教程视频_PHP Xdebug 是什么?