STL函数对象

作者: Jianbaozi | 来源:发表于2019-03-08 14:54 被阅读0次
#include "../std_lib_facilities.h"
struct Record {
    string firstname;
    char* lastname;
    Record(string s, char* p) :firstname(s), lastname(p) {}
    void print() { cout << firstname << " " << lastname <<'\n'; }
};
bool f(Record& r) { return r.firstname == "Diana"; } //函数当作参数传递
struct cmp_fname {    //函数对象
    bool operator()(const Record& a,const Record& b)const
    {
        return a.firstname < b.firstname;
    }
};
/*struct cmp_lname  {
    bool operator()(const Record& a, const Record& b)const
    {
        return strncmp(a.lastname, b.lastname,20) < 0;
    }
};*/
bool cmp_lname(const Record& a, const Record& b)
{
    return strncmp(a.lastname, b.lastname, 20) < 0;
}
int main(){
    vector<Record> vr = { 
Record{"Arthur","Curry"},
Record{"Barry","Allen"},
Record{"Diana","Prince"},
Record{"Clark","Kent"}
 };
    cout << "sort by first name:" << '\n';
    cout << "--------------------------" << '\n';
    sort(vr.begin(), vr.end(), cmp_fname()); //注意 cmp_fname()括号
    for (auto r : vr)
        r.print();
    cout <<'\n'<< "sort by last name:" << '\n';
    cout << "--------------------------" << '\n';
    sort(vr.begin(), vr.end(), cmp_lname);
    for (auto r : vr)
        r.print();
    cout << "--------------------------" << '\n';
    auto p=find_if(vr.begin(), vr.end(), f); //做参数时不要加(),会变成函数调用
    cout << "position " << p - vr.begin() + 1 << endl;
    system("pause");
    return 0;
}

输出:

sort by first name:
--------------------------
Arthur Curry
Barry Allen
Clark Kent
Diana Prince

sort by last name:
--------------------------
Barry Allen
Arthur Curry
Clark Kent
Diana Prince
--------------------------
position 4
请按任意键继续. . .

相关文章

  • 【Effective STL(6)】仿函数、仿函数类、函数等

    38 把仿函数类设计为用于值传递 STL函数对象在函数指针之后成型,因此STL习惯传给函数和从函数返回时,函数对象...

  • STL函数对象

    输出:

  • 一些面试题记录

    STL1、对STL有哪些了解2、STL中的内存管理3、什么是函数对象,用在哪些情况4、用过哪些STL算法5、基本容...

  • 32 STL (十)函数对象

    函数对象概念 ()重载的类,实现函数功能,和我们之前讲的仿函数是一个东西,可以有参数,也可以有返回值,因为还可以记...

  • STL算法之函数对象

    概述 函数对象又叫仿函数:重载了函数调用运算符()的类实例化的对象。该对象和()结合触发operator()函数的...

  • STL学习笔记之算法(二)

    仿函数、仿函数类、函数等 条款38:把仿函数类设计为用于值传递 STL中的习惯是当传给函数和从函数返回时函数对象也...

  • C++笔记九(STL与泛型编程)

    本周内容(1)迭代器的分类(category)(2)迭代器分类对算法的影响(3)STL算法(4)仿函数/函数对象(...

  • GeekBand-STL 第2周

    stl的整体结构: 内存分配器,迭代器,容器,仿函数,算法,适配器 仿函数与函数的区别:本质是一个对象,opera...

  • boost::ref

    背景 STL和Boost中的算法和函数大量使用了函数对象作为判断式或谓词参数,而这些参数都是传值语义,算法或函数在...

  • STL:

    STL 算法的操作参数可以用函数对象, 也可以用函数指针: (模板)函数实参推断可以推断出操作实参的类型 不用记算...

网友评论

    本文标题:STL函数对象

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