0.大纲

注意:函数对象和仿函数指的是一个东西.
1.Function Object(函数对象-仿函数)的概念
所谓function object(或者说functor),是一个定义了operator()的类的一个对象. FunctionObjectType fo;
... fo(...); 
!!!!注意:表达式fo()是调用函数对象fo的operator(),而非调用函数fo(). 

函数对象的一般写法:
class FunctionObjectType { public: void operator() () { statements } };
1.1.1 仿函数相对于一般函数的优点
仿函数的优点: 1.仿函数是对象,可以拥有成员函数和成员变量,即仿函数拥有状态; 2.每个仿函数都有自己的类型;
3.仿函数通常比一般函数快(很多信息编译期确定).

1.1.2 以仿函数为排序准则 
#include <iostream> #include <string> #include <deque> #include <set>
#include <algorithm> using namespace std; /*Person类*/ class Person { private:
string fn; // first name string ln; // last name public: Person() {}
Person(const string &f, const string &n) : fn(f), ln(n) {} string firstname()
const; string lastname() const; }; inline string Person::firstname() const {
return fn; } inline string Person::lastname() const { return ln; } ostream
&operator<<(ostream &s, const Person &p) { s << "[" << p.firstname() << " " <<
p.lastname() << "]"; return s; } /* class for function predicate * - operator
() returns whether a person is less than another person */ class
PersonSortCriterion { public: bool operator()(const Person &p1, const Person
&p2) const { /* a person is less than another person * - if the last name is
less * - if the last name is equal and the first name is less */ return
p1.lastname() < p2.lastname() || ( p1.lastname() == p2.lastname() &&
p1.firstname() < p2.firstname()); } }; int main() { Person p1("nicolai",
"josuttis"); Person p2("ulli", "josuttis"); Person p3("anica", "josuttis");
Person p4("lucas", "josuttis"); Person p5("lucas", "otto"); Person p6("lucas",
"arm"); Person p7("anica", "holle"); // declare set type with special sorting
criterion typedef set<Person, PersonSortCriterion> PersonSet; // create such a
collection PersonSet coll; coll.insert(p1); coll.insert(p2); coll.insert(p3);
coll.insert(p4); coll.insert(p5); coll.insert(p6); coll.insert(p7); // do
something with the elements // - in this case: output them cout << "set:" <<
endl; PersonSet::iterator pos; for (pos = coll.begin(); pos != coll.end();
++pos) { cout << *pos << endl; } } /* 注释: 这里的set coll使用特殊排序准则
PersonSortCriterion,而它正是一个function object class.
PersonSortCriterion这么定义operator():先比较两人的姓,如果相等再比较其名. coll构造函数会自动产生class
PersonSortCriterion的一个实例(instance),所有元素都 将以此为排序准则进行排序.
注意,排序准则PersonSortCriterion是个class,所以你可以把它当作set的template实参.
如果以寻常函数担任排序准则,就无法做到这一点. "以上述类型作为排序准则"的所有set,都拥有属于自己的独一无二的类型. 无法将这个set拿
来和"拥有不同排序准则"的其他set合并或赋值. 虽然无论做什么都无法回避set的自动排序特 性,但可以设计出"表现不同的排序准则却有着相同类型"的仿函数.
*/

技术
今日推荐
PPT
阅读数 126
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信