注意:函数对象和仿函数指的是一个东西.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#include #include #include #include using namespace std; 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 PersonSortCriterion { public: bool operator()(const Person &p1, const Person &p2) const { 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 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; } }



