Sign in with Google to keep private notes

Lambdas C++

Lambdas In Short

friend bool operator< (const Person&, const Person&);

then std::sort(coll.begin(), coll.end());

but now we want to pass a function in, std::sort(coll.begin(), coll.end(), lessPerson);

and you'd define a function bool lessPerson(const Person& p1, const Person & p2); but the problem is you couldn't define functions within functions. In C++ 11 they came up with lambdas to solve it. Where you need the function as an argument, as an object, as a paramter, you specify inline where it is.

[] (const Person& p1, const Person& p2) {
    //blablablabla, put whatever you want here
};

These are better optimised than taking functions because the local lambdas have only local scope. They are always defined (declared and defined, hah) and it becomes easier for your compiler to optimise this section of the code.

This is the beginning of templated programming in C++.

These are 3 components: container, iterator, and callable. The third of which includes functions, function pointers, raw functions, raw function pointers, and lambdas. A lambda is, we will see, an object that behaves like a function.=

Examples of seperate responsibilities:

std::vector<int> src{1, 2, 3, 4};
std::list<int> dest;

std::copy_if(
    src.begin(), src.end(),       // Source iterators
    std::back_inserter(dest),     // Destination iterator
    [](int x) { return x % 2 == 0; } // Callable
);

// dest = {2, 4}

You can treat a lambda as kind of a function object

auto isOdd = [] (int elem) {
    return elem % 2 == 0;
};

(Apparently auto in this case is faster than any decision you could make here)

Q: Why am i not allowed to define functions in line, but i can define a lambda in line

You can use lambdas like functions and functions like lambdas because they both fall under the callable.

std::vector<std::string> coll {"Here", "are", "cities", "Berlin", "LA", "London", "Cologne"};

std::sort(coll.begin(), coll.end(),
    [](const std::string& s1, const std::string& s2) {
        return std::lexicographical_compare(
            s1.begin(), s1.end(),
            s2.begin(), s2.end(),
            [](char c1, char c2) {
                return std::toupper(c1) < std::toupper(c2);
            }
        );
    }
);

An STL algorithm can accept a lambda that calls another STL algorithm with another lambda. Here, std::sort compares strings, while std::lexicographical_compare compares their characters.

I'm noticing the lambdas each receive individual items in the container being iterated. coll std::sort acts on coll, and each element in coll is a can bind to the std::string& rval.

std::lexicographical_compare acts on string containers. Where iterators of that string refer to chars. So binding it to [] (char c1, char c2) makes sense there.

And I guess there's a slightly more interesting way to do this which is to use ranges functions in C++20 which assume you want to iterate across the whole range, and give you some extra firepower in just converting certain parts of your range

int main()
{
    std::vector<std::string> coll {"Here", "are", "cities", "Berlin", "LA", "London", "Cologne"};
    std::ranges::sort(coll,
        [] (const std::string& s1, const std::string& s2) {
            auto toUpper = [] (char c) { return c.toupper(c); };
            return std::ranges::lexicographical_compare(s1, s2, std::less{}, toUpper, toUpper); 
        });
}

std::ranges argument order: container, lambda, additional projection function on each item in the lambda. I think we need to pass std::less{} even if its default because we're trying to get the toUpper lambda into its right positional argument.

Gets down to business faster, I think.

Also you can declare a lambda and hand it over to an unordered_set.

std::unordered_set<MyType, decltype(hashFunc)> coll;

Stateful...functions...?

Consider std::count_if:

int max = 30;

auto predicate = [max](int x) {
    return x < max;
};

std::count_if(v.begin(), v.end(), predicate);

std::count_if expects a function taking exactly one argument: the element being examined.

You might instead try:

bool predicate(int x, int max) {
    return x < max;
}

std::count_if(v.begin(), v.end(), predicate); // ERROR

Under the scenes

class lambda??? {
    public:
        lambda();
        int operator () (int x, int y) const {
            //do whatever you said you would just now 
    };
}

//so initialising and assigning a lambda, its a shortcut for instantiating an object
auto add = lambda???{};

A lambda is an object of a type of a class. Its a class object. Each lambda is a shortcut for that. Compiler will decide on the name for you, and it usually has some fucked up hash object.

Nonmenclature: The class is called a closure type. The instance of it is closure object

Another advantage over functions that lambdas have

call(printFunc, v);               // ERROR
call(printFunc<decltype(v)>, v);  // OK
call(printLmbd, v);  // OK

because printFunc is a template, and it doesn't exist yet, so

the lambda came into existence as an object when we did auto printLmbd = [] (//stuff);

The lambdas capture stuff by value, not by reference. Capture is performed when the lambda is created. The capture is copy constructed. Of course, if you want to you can capture by reference. with

&amp;sum

or [&] to do it for all of them. Just be mindful this can blow up in your face because the lambda can now perma affect it.

[&coll = std::asconst(coll)] will help you do your stupid const references and get your performance win

auto changed = [prev = 0] (auto val) mutable {
    bool changed = val == prev;
    prev = val;
    return changed; 
}

This makes your lambdas stateful (stateless is when the lambda returns the same thing given the same input. Stateful is whatever is not stateless). But it can be dangerous for, uh, reasons.

Also cool thing: since lambdas are just classes treated as functions, stateful lambdas have different behaviours depending on if the function you're passing into gets the callable by value or by reference.

Lambdas in long

As described on learncpp:

[] () -> return_type {}

if return type is not specified the return is taken as auto. Which you can do

If return type is specified then you would have to include the () (even if your lambda doesnt actually take in any parameters)

although, if it doesnt, then you can just use the lambda

Best practice:

Following the best practice of defining things in the smallest scope and closest to first use, lambdas are preferred over normal functions when we need a trivial, one-off function to pass as an argument to some other function.

Lambdas are functors. Functors are a special type of object with overloaded () operators which will allow them to be called as if they were functions. Fun.

You can capture lambdas like this. Why you would ever want to do this is beyond me but yeah you can

#include <functional>

int main()
{
  // A regular function pointer. Only works with an empty capture clause (empty []).
  double (*addNumbers1)(double, double){
    [](double a, double b) {
      return a + b;
    }
  };

  addNumbers1(1, 2);

  // Using std::function. The lambda could have a non-empty capture clause (discussed next lesson).
  std::function addNumbers2{ // note: pre-C++17, use std::function<double(double, double)> instead
    [](double a, double b) {
      return a + b;
    }
  };

  addNumbers2(3, 4);

  // Using auto. Stores the lambda with its real type. No overhead.
  auto addNumbers3{
    [](double a, double b) {
      return a + b;
    }
  };

  addNumbers3(5, 6);

  return 0;
}

 

If we want to pass the lambda to another function (my personal favourite is using ol' reliable const auto&)

#include <functional>
#include <iostream>

// Case 1: use a `std::function` parameter
void repeat1(int repetitions, const std::function<void(int)>& fn)
{
    for (int i{ 0 }; i < repetitions; ++i)
        fn(i);
}

// Case 2: use a function template with a type template parameter
template <typename T>
void repeat2(int repetitions, const T& fn)
{
    for (int i{ 0 }; i < repetitions; ++i)
        fn(i);
}

// Case 3: use the abbreviated function template syntax (C++20)
void repeat3(int repetitions, const auto& fn)
{
    for (int i{ 0 }; i < repetitions; ++i)
        fn(i);
}

// Case 4: use function pointer (only for lambda with no captures)
void repeat4(int repetitions, void (*fn)(int))
{
    for (int i{ 0 }; i < repetitions; ++i)
        fn(i);
}

int main()
{
    auto lambda = [](int i)
    {
        std::cout << i << '\n';
    };

    repeat1(3, lambda);
    repeat2(3, lambda);
    repeat3(3, lambda);
    repeat4(3, lambda);

    return 0;
}

(Ill go with 3 because its easier than 2, less overhead than 1, and covers more cases than 4)

(1 causes overhead because calling the lambda performs implicit conversion)

Each time you call a lambda with a different parameter you will be calling a different functor type. So the static variable belonging to that functor type does not persist

#include <algorithm>
#include <array>
#include <iostream>
#include <string_view>

int main()
{
  // Print a value and count how many times @print has been called.
  auto print{
    [](auto value) {
      static int callCount{ 0 };
      std::cout << callCount++ << ": " << value << '\n';
    }
  };

  print("hello"); 
  print("world"); 
  print("i'm so excited to finally be here");

  print(1); 
  print(2); 

  print("ding dong"); 

  return 0;
}

0: hello
1: world
2: i'm so excited to finally be here
0: 1
1: 2
3: ding dong

Without the [&] capture clause, lambdas can only access objects which

  1. static (or thread local) storage duration (this includes global variables and static locals)
  2. are constexpr (explicitly or implicitly)

A lambda has its own scope because its body defines a function body (operator()).
If you want to capture a variable you have to include it in the capture clause
They default to const expression so you need to add the mutable keyword so they can be affected within their function bodies

// Capture health and armor by value, and enemies by reference.
[health, armor, &enemies](){};

// Capture enemies by reference and everything else by value.
[=, &enemies](){};

// Capture armor by value and everything else by reference.
[&, armor](){};

// Illegal, we already said we want to capture everything by reference.
[&, &armor](){};

// Illegal, we already said we want to capture everything by value.
[=, armor](){};

// Illegal, armor appears twice.
[armor, &health, &armor](){};

// Illegal, the default capture has to be the first element in the capture group.
[armor, &](){};

why do they do this? LLM:

Primarily safety and clarity, not performance.

Lambdas can outlive the scope in which they were created, so automatically capturing everything could introduce:

  1. Dangling references: A lambda might access a local variable that has already been destroyed.
  2. Unexpected copies: Capturing large objects by value could be expensive.
  3. Hidden dependencies: It becomes harder to tell which external variables a lambda relies on.
  4. Unintended state: Captured variables become part of the lambda object's state.

C++ therefore requires you to explicitly specify a capture policy.

Warning

Be extra careful when you capture variables by reference, especially with a default reference capture. The captured variables must outlive the lambda

#include <iostream>
#include <string>

// returns a lambda
auto makeWalrus(const std::string& name)
{
  // Capture name by reference and return the lambda.
  return [&]() {
    std::cout << "I am a walrus, my name is " << name << '\n'; // Undefined behavior
  };
}

int main()
{
  // Create a new walrus whose name is Roofus.
  // sayName is the lambda returned by makeWalrus.
  auto sayName{ makeWalrus("Roofus") };

  // Call the lambda function that makeWalrus returned.
  sayName();

  return 0;
}

the lifetime of the temporary string Roofus dies after makeWalrus so calling sayName leaves us attempting to use a dangling pointer

to look into:
std::function can be used to bind to the lambda. even if it does capture. but why?
std::ref is a "reference wrapper" allowing you to treat variables as if they were references...what does that even mean...

Try to avoid mutable lambdas. Non-mutable lambdas are easier to understand and don’t suffer from the above issues, as well as more dangerous issues that arise when you add parallel execution.

All else be damned you can't do this:

int main() {
    auto foo = [](double a) {return a; };
    foo = [](double a) {return a + 1; };

    std::cout << foo(static_cast<double>(3)) << std::endl;
}

Because the first foo and the second foo have different lambda types. Not that the compiler error message telling you it can't add a main()::lambda<double> to a main()::lambda<double> really helps you figure that out.

Articles to read next