STL - C++ 11的Lambda表达式(下)

简介: 关于lambda的基础知识,请参考上一篇的地址如下: http://www.cnblogs.com/davidgu/p/4825625.html   我们再举个STL使用Lambda来进行排序的例子,如下: Person.

关于lambda的基础知识,请参考上一篇的地址如下:

http://www.cnblogs.com/davidgu/p/4825625.html

 

我们再举个STL使用Lambda来进行排序的例子,如下:

Person.h

#ifndef _Domain_Models_Person_H_
#define _Domain_Models_Person_H_

#include <iostream>
#include <string>
#include <deque>

using namespace std;

class Person 
{
    friend ostream& operator<< (ostream& s, const Person& p);
private:
    string fn;    // first name
    string ln;    // last name
    int age;
public:
    Person() { }
    Person(const string& f, const string& n)
        : fn(f), ln(n) 
    {
    }
    string firstname() const;
    string lastname() const;
    int getAge() const;
    void setAge(int a);
    static bool sortByName(const Person& p1, const Person& p2);
    static bool sortByAge(const Person& p1, const Person& p2);
    static void sortDequeByName(deque<Person> &persons);
    static void sortDequeByAge(deque<Person> &persons);
    static void printPersonDeques(deque<Person> persons);
};

#endif

 

Person.cpp

#include <algorithm>
#include "Person.h"

inline string Person::firstname() const 
{
    return fn;
}

inline string Person::lastname() const 
{
    return ln;
}

inline int Person::getAge() const
{
    return age;
}

void Person::setAge(int a)
{
    age = a;
}

/* binary function predicate:
* - returns whether a person is less than another person
*/
bool Person::sortByName(const Person& p1, const Person& p2)
{
    /* 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());
}


// another binary predicate
bool Person::sortByAge(const Person& p1, const Person& p2)
{
    return p1.getAge() < p2.getAge();
}

void Person::sortDequeByName(deque<Person> &persons)
{
    // sort elements
    sort(persons.begin(), persons.end(),    // range
        Person::sortByName);       // sort criterion
}

void Person::sortDequeByAge(deque<Person> &persons)
{
    // sort elements
    sort(persons.begin(), persons.end(),    // range
        Person::sortByAge);       // sort criterion
}

ostream& operator<< (ostream& s, const Person& p)
{
    s << "[" << p.lastname() << ", " << p.firstname() << ", " << p.getAge() << "]";
    return s;
}

void Person::printPersonDeques(deque<Person> persons)
{
    deque<Person>::iterator pos;
    for (pos = persons.begin(); pos != persons.end(); ++pos)
    {
        cout << *pos << endl;
    }
}

 

LambdaTest.cpp

#include <algorithm>
#include <deque>
#include <iostream>
#include "LambdaTest.h"
#include "../../Core/ContainerUtil.h"

using namespace std;

void LambdaTest::sortByLambda()
{
    // create some persons
    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");
    p1.setAge(20);
    p2.setAge(30);
    p3.setAge(18);
    p4.setAge(2);
    p5.setAge(22);
    p6.setAge(35);
    p7.setAge(95);

    // insert person into collection coll
    deque<Person> coll;
    coll.push_back(p1);
    coll.push_back(p2);
    coll.push_back(p3);
    coll.push_back(p4);
    coll.push_back(p5);
    coll.push_back(p6);
    coll.push_back(p7);

    cout << "persons before sort:" << endl;
    Person::printPersonDeques(coll);

    // sort Persons according to lastname (and firstname)
    sort(coll.begin(), coll.end(),                // range
        [](const Person& p1, const Person& p2) { // sort criterion
        return p1.lastname()<p2.lastname() ||
            (p1.lastname() == p2.lastname() &&
            p1.firstname()<p2.firstname());
    });

    cout << "persons after sort by name:" << endl;
    Person::printPersonDeques(coll);

    // sort Persons according to age
    sort(coll.begin(), coll.end(),                // range
        [](const Person& p1, const Person& p2) { // sort criterion
        return p1.getAge() < p2.getAge();
    });

    cout << "persons after sort by age:" << endl;
    Person::printPersonDeques(coll);
}

void LambdaTest::run()
{
    printStart("sortByLambda()");
    sortByLambda();
    printEnd("sortByLambda()");
}

 

运行结果:

---------------- sortByLambda(): Run Start ----------------
persons before sort:
[josuttis, nicolai, 20]
[josuttis, ulli, 30]
[josuttis, anica, 18]
[josuttis, lucas, 2]
[otto, lucas, 22]
[arm, lucas, 35]
[holle, anica, 95]
persons after sort by name:
[arm, lucas, 35]
[holle, anica, 95]
[josuttis, anica, 18]
[josuttis, lucas, 2]
[josuttis, nicolai, 20]
[josuttis, ulli, 30]
[otto, lucas, 22]
persons after sort by age:
[josuttis, lucas, 2]
[josuttis, anica, 18]
[josuttis, nicolai, 20]
[otto, lucas, 22]
[josuttis, ulli, 30]
[arm, lucas, 35]
[holle, anica, 95]
---------------- sortByLambda(): Run End ----------------

 

目录
相关文章
|
2月前
|
缓存 算法 程序员
C++STL底层原理:探秘标准模板库的内部机制
🌟蒋星熠Jaxonic带你深入STL底层:从容器内存管理到红黑树、哈希表,剖析迭代器、算法与分配器核心机制,揭秘C++标准库的高效设计哲学与性能优化实践。
C++STL底层原理:探秘标准模板库的内部机制
|
5月前
|
程序员 编译器 C++
【实战指南】C++ lambda表达式使用总结
Lambda表达式是C++11引入的特性,简洁灵活,可作为匿名函数使用,支持捕获变量,提升代码可读性与开发效率。本文详解其基本用法与捕获机制。
181 44
|
9月前
|
编译器 C++ 容器
【c++丨STL】基于红黑树模拟实现set和map(附源码)
本文基于红黑树的实现,模拟了STL中的`set`和`map`容器。通过封装同一棵红黑树并进行适配修改,实现了两种容器的功能。主要步骤包括:1) 修改红黑树节点结构以支持不同数据类型;2) 使用仿函数适配键值比较逻辑;3) 实现双向迭代器支持遍历操作;4) 封装`insert`、`find`等接口,并为`map`实现`operator[]`。最终,通过测试代码验证了功能的正确性。此实现减少了代码冗余,展示了模板与仿函数的强大灵活性。
247 2
|
9月前
|
存储 算法 C++
【c++丨STL】map/multimap的使用
本文详细介绍了STL关联式容器中的`map`和`multimap`的使用方法。`map`基于红黑树实现,内部元素按键自动升序排列,存储键值对,支持通过键访问或修改值;而`multimap`允许存在重复键。文章从构造函数、迭代器、容量接口、元素访问接口、增删操作到其他操作接口全面解析了`map`的功能,并通过实例演示了如何用`map`统计字符串数组中各元素的出现次数。最后对比了`map`与`set`的区别,强调了`map`在处理键值关系时的优势。
472 73
|
8月前
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
296 12
|
10月前
|
存储 缓存 C++
C++ 容器全面剖析:掌握 STL 的奥秘,从入门到高效编程
C++ 标准模板库(STL)提供了一组功能强大的容器类,用于存储和操作数据集合。不同的容器具有独特的特性和应用场景,因此选择合适的容器对于程序的性能和代码的可读性至关重要。对于刚接触 C++ 的开发者来说,了解这些容器的基础知识以及它们的特点是迈向高效编程的重要一步。本文将详细介绍 C++ 常用的容器,包括序列容器(`std::vector`、`std::array`、`std::list`、`std::deque`)、关联容器(`std::set`、`std::map`)和无序容器(`std::unordered_set`、`std::unordered_map`),全面解析它们的特点、用法
C++ 容器全面剖析:掌握 STL 的奥秘,从入门到高效编程
|
9月前
|
存储 算法 C++
【c++丨STL】set/multiset的使用
本文深入解析了STL中的`set`和`multiset`容器,二者均为关联式容器,底层基于红黑树实现。`set`支持唯一性元素存储并自动排序,适用于高效查找场景;`multiset`允许重复元素。两者均具备O(logN)的插入、删除与查找复杂度。文章详细介绍了构造函数、迭代器、容量接口、增删操作(如`insert`、`erase`)、查找统计(如`find`、`count`)及`multiset`特有的区间操作(如`lower_bound`、`upper_bound`、`equal_range`)。最后预告了`map`容器的学习,其作为键值对存储的关联式容器,同样基于红黑树,具有高效操作特性。
375 3
|
10月前
|
存储 算法 C++
【c++丨STL】priority_queue(优先级队列)的使用与模拟实现
本文介绍了STL中的容器适配器`priority_queue`(优先级队列)。`priority_queue`根据严格的弱排序标准设计,确保其第一个元素始终是最大元素。它底层使用堆结构实现,支持大堆和小堆,默认为大堆。常用操作包括构造函数、`empty`、`size`、`top`、`push`、`pop`和`swap`等。我们还模拟实现了`priority_queue`,通过仿函数控制堆的类型,并调用封装容器的接口实现功能。最后,感谢大家的支持与关注。
546 1
|
11月前
|
C++ 容器
【c++丨STL】stack和queue的使用及模拟实现
本文介绍了STL中的两个重要容器适配器:栈(stack)和队列(queue)。容器适配器是在已有容器基础上添加新特性或功能的结构,如栈基于顺序表或链表限制操作实现。文章详细讲解了stack和queue的主要成员函数(empty、size、top/front/back、push/pop、swap),并提供了使用示例和模拟实现代码。通过这些内容,读者可以更好地理解这两种数据结构的工作原理及其实现方法。最后,作者鼓励读者点赞支持。 总结:本文深入浅出地讲解了STL中stack和queue的使用方法及其模拟实现,帮助读者掌握这两种容器适配器的特性和应用场景。
270 21
|
10月前
|
存储 算法 C++
深入浅出 C++ STL:解锁高效编程的秘密武器
C++ 标准模板库(STL)是现代 C++ 的核心部分之一,为开发者提供了丰富的预定义数据结构和算法,极大地提升了编程效率和代码的可读性。理解和掌握 STL 对于 C++ 开发者来说至关重要。以下是对 STL 的详细介绍,涵盖其基础知识、发展历史、核心组件、重要性和学习方法。