Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Recursion Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess STL Modern C++ Misc Books ----

Lambdas


Contents

Introduction

Sometimes we need a function that will be used in a very limited way. Lambdas allow us to write an expression that will be used as a function. Anything that lambdas can do can be done by functions pre C++11
This paradigm is known as functional programming. We had function objects ( functors ) that involved creating a class and an operator function insided it. Now we can create a function in a much more simplistic and concise way. If the function is only going to be used in a limited manner then we have localized it's definition.

File: use_case1.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std ;

class Person {
    public:
     string name;
     int age;
};


bool sortPerson (const Person& p1, const Person& p2)
 {
        if (p1.age != p2.age) {
            return p1.age < p2.age; // Sort by age
        }
        return p1.name < p2.name; // If ages are equal, sort by name
}


int main()
{

    vector<Person> people = {
        {"Jon", 60 },
        {"Von", 60 },
        {"Neumann", 60 },
        {"Turing", 22 },
        {"Alan", 22 }

    };

    sort(people.begin(), people.end(), sortPerson )  ;
    for (const auto& person : people) {
        cout << person.name << " (" << person.age << ")" << endl;
    }

    cout << "----------------" << endl ;
    // Sort people by age in ascending order, then by name in ascending order
    sort(people.begin(), people.end(),
    [](const Person& p1, const Person& p2)
    {
        if (p1.age != p2.age) {
            return p1.age < p2.age; // Sort by age
        }
        return p1.name < p2.name; // If ages are equal, sort by name
    });

    for (const auto& person : people) {
        cout << person.name << " (" << person.age << ")" << endl;
    }

    return 0;
}
$ g++ use_case1.cpp ; ./a.exe
Alan (22)
Turing (22)
Jon (60)
Neumann (60)
Von (60)
----------------
Alan (22)
Turing (22)
Jon (60)
Neumann (60)
Von (60)