栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【C++标准库】10.STL函数对象(仿函数)及Lambda

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【C++标准库】10.STL函数对象(仿函数)及Lambda

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 
#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;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847058.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号