美文网首页
STL Function Objects and Using L

STL Function Objects and Using L

作者: 龙遁流 | 来源:发表于2017-02-04 15:16 被阅读0次

函数对象是定义了operator()函数的类,相比普通函数具有多实例,可定制,比函数指针更快的特点。

默认传递给stl算法的函数对象参数是值传递的,但可以自定义算法模板传递参数为引用类型,使得外部可以访问到函数对象的内部状态(或使用for_each的返回值)

函数对象一般用来提供全局的使用,lambda表达式用于局部的使用

预定义的函数对象

函数适配器

bind的特点

• Adapt and compose new function objects out of existing or predefined function objects

• Call global functions

• Call member functions for objects, pointers to objects, and smart pointers to objects

bind将参数绑定到可调用对象上,参数的占位符定义在std::placeholders上的_1,_2等;bind表达式可以直接调用,嵌套;bind内部的参数是值传递,可以使用ref或cref转换为引用

例如

auto plus10 = std::bind(std::plus<int>(), std::placeholders::_1, 10);

plus10(7);//将7作为std::plus<int>()第一个参数

也可以用bind绑定数据成员

int sum= accumulate (coll.begin(), coll.end(), 0, bind(

plus<int>(),_1,bind(&map<string, int>::value_type::second,_2)

));

mem_fn()绑定类的成员函数

例如

std::for_each (coll.begin(), coll.end(), std::mem_fn(&Person::print));

std::mem_fn(&Person::print)(n); // calls n.print()

std::mem_fn(&Person::print2)(n,"Person: "); // calls n.print2("Person: ")

相关文章

网友评论

      本文标题:STL Function Objects and Using L

      本文链接:https://www.haomeiwen.com/subject/ipulittx.html