🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Lambdas and algorithms: sort, find_if, accumulate

Learn the capture rules of lambdas in depth; use std::sort, std::find_if and std::accumulate on data made of structs, and store lambdas in a rule table with std::function.

You first saw lambdas in the introduction to the STL: we gave count_if a small function that asked "is it greater than 24?". Real data is a bit more complex. In a panel schedule every circuit has a name, a current and a fuse rating; you ask questions like "sort by current", "find the first circuit that exceeds its fuse" or "calculate the total power". In this lesson we will look at lambda capture rules in detail, then use std::sort, std::find_if and std::accumulate on a vector of structs. Finally we will store lambdas in a variable and build a table of alarm rules.

Anatomy of a lambda and capturing

A lambda has four parts: [capture](parameters) -> returnType { body }. The return type is usually left out; the compiler works it out from the return statement. The capture is where most mistakes happen: a lambda either copies an outside variable or refers to it. The difference shows up when the variable changes later.

#include <iostream>

int main() {
    double esik = 24.0;
    auto kopya = [esik](double x) { return x > esik; };   // o anki deger kopyalanir
    auto ref = [&esik](double x) { return x > esik; };    // degiskenin kendisine bakar
    esik = 30.0;

    std::cout << std::boolalpha;
    std::cout << "kopya(25): " << kopya(25.0) << '\n';
    std::cout << "ref(25):   " << ref(25.0) << '\n';

    int sayac = 0;
    auto say = [&sayac]() { ++sayac; };
    say();
    say();
    say();
    std::cout << "sayac: " << sayac << '\n';

    auto donustur = [](int ham) -> double { return ham * 3.3 / 1023; };
    std::cout << "512 -> " << donustur(512) << " V\n";
    return 0;
}
kopya(25): true
ref(25):   false
sayac: 3
512 -> 1.65161 V

When kopya (copy) was created, the threshold was 24, and that value was copied into the lambda; even though the threshold later became 30, the copy decided based on 24. ref looks at the variable itself on every call and saw 30. The say (count) lambda captured the counter by reference, so it really increased the outside variable. Had we captured by copy, the compiler would not have allowed the ++sayac line, because values captured by copy are read-only by default. In the last lambda we wrote the return type explicitly with -> double.

Instead of listing every variable, you can also use a default capture: [=] copies every outside variable used in the body, and [&] refers to all of them. It is handy for short lambdas, but it hides what is captured; you may copy a large vector without noticing, or change a variable you did not mean to. That is why listing the captured variables explicitly is easier to read. If you need to change a value captured by copy inside the lambda, mark the lambda mutable: [n]() mutable { return ++n; }. The lambda then increases its own copy; the outside n does not change. A small counter that produces the next reading number on every call can be written this way, for example.

A practical rule: if the lambda is used immediately and thrown away (as an argument to an algorithm), capturing by reference is safe. If the lambda will be stored and called later, capture by copy unless you are sure the captured variables will still be alive by then.

Algorithms with structs: find_if, sort, accumulate

Let's keep the circuits of a distribution panel in a vector and ask three questions.

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>

struct Devre {
    std::string ad;
    double akim;          // A
};

int main() {
    std::vector<Devre> pano = {
        {"aydinlatma", 6.5}, {"priz-1", 14.2}, {"klima", 9.8},
        {"priz-2", 11.0}, {"kombi", 1.2}};
    const double gerilim = 230.0;
    const double sigorta = 10.0;

    // 1) Sigorta degerini asan ilk devre (pano sirasina gore)
    auto it = std::find_if(pano.begin(), pano.end(),
                           [sigorta](const Devre& d) { return d.akim > sigorta; });
    if (it != pano.end()) {
        std::cout << "Ilk asim: " << it->ad << " (" << it->akim << " A)\n";
    }

    // 2) Akima gore buyukten kucuge sirala
    std::sort(pano.begin(), pano.end(),
              [](const Devre& a, const Devre& b) { return a.akim > b.akim; });
    for (const auto& d : pano) {
        std::cout << "  " << d.ad << ": " << d.akim << " A\n";
    }

    // 3) Toplam guc: accumulate + lambda
    double toplamGuc = std::accumulate(pano.begin(), pano.end(), 0.0,
        [gerilim](double toplam, const Devre& d) { return toplam + d.akim * gerilim; });
    std::cout << std::fixed << std::setprecision(1);
    std::cout << "Toplam guc: " << toplamGuc / 1000.0 << " kW\n";
    return 0;
}
Ilk asim: priz-1 (14.2 A)
  priz-1: 14.2 A
  priz-2: 11 A
  klima: 9.8 A
  aydinlatma: 6.5 A
  kombi: 1.2 A
Toplam guc: 9.8 kW

Let's look at each algorithm separately:

  • std::find_if returns an iterator to the first element that satisfies the condition; if none does, it returns end(). That is why we always compared the result with end() before using it. The iterator behaves like a pointer, so we reached the fields with it->ad. Two circuits exceed the fuse (priz-1 and priz-2); priz-1, which comes first in panel order, was found.
  • std::sort cannot sort a struct on its own, because it does not know which of two Devre objects is "smaller". The comparator lambda tells it: "should a come before b?" a.akim > b.akim sorts from largest to smallest. The comparator must return false for equal elements; writing >= is undefined behaviour.
  • The four-parameter form of std::accumulate lets you decide with a lambda how the adding is done. The lambda takes two things, the total so far and the next element, and returns the new total. The total current is 42.7 A, so the power is 42.7 × 230 = 9821 W, about 9.8 kW. Here too it is critical that the initial value is 0.0.

Storing lambdas: std::function

Every lambda has its own unique, unnamed type generated by the compiler. So to put different lambdas in the same vector, you need a common container: std::function from the <functional> header. std::function<bool(double)> means "anything callable that takes a double and returns a bool". With it we can keep the alarm rules of a voltage monitor as data:

#include <functional>
#include <initializer_list>
#include <iostream>
#include <string>
#include <vector>

struct Kural {
    std::string mesaj;
    std::function<bool(double)> kosul;
};

int main() {
    const double nominal = 230.0;
    std::vector<Kural> kurallar = {
        {"dusuk gerilim", [nominal](double v) { return v < nominal * 0.9; }},
        {"yuksek gerilim", [nominal](double v) { return v > nominal * 1.1; }},
        {"sebeke yok", [](double v) { return v < 10.0; }}};

    for (double v : {231.0, 198.5, 0.0}) {
        std::cout << v << " V:";
        bool sorun = false;
        for (const auto& k : kurallar) {
            if (k.kosul(v)) {
                std::cout << ' ' << k.mesaj;
                sorun = true;
            }
        }
        std::cout << (sorun ? "\n" : " normal\n");
    }
    return 0;
}
231 V: normal
198.5 V: dusuk gerilim
0 V: dusuk gerilim sebeke yok

To add a new alarm you do not have to touch the loop; you add a row to the table. 0 V triggered two rules at once ("low voltage" and "no mains"), because zero is both below 207 and below 10. std::function has a small call overhead; if you pass a lambda straight to an algorithm you do not need it, use it only when storing.

Common mistakes

  • Capturing a local variable by reference and storing the lambda. If a function returns a lambda that captures with [&esik], esik disappears when the function ends and the lambda is left with a dangling reference. Capture by copy in stored lambdas.
  • Thinking remove_if deletes elements. std::remove_if moves the elements to keep to the front and returns the new logical end; the vector's size does not change. To really delete: v.erase(std::remove_if(v.begin(), v.end(), condition), v.end());.
  • Using the result of find_if without checking it. If no element is found, the result is end(), and writing it->ad is undefined behaviour.

Exercise

A temperature log has six readings (minute, temperature): (0, 22.5), (5, 23.0), (10, 21.5), (15, 24.0), (20, 22.0), (25, 25.5). Do three things: use find_if to find the minute when the temperature first exceeds 23.5; compute the average with accumulate and a lambda; sort the readings by temperature from highest to lowest with sort and print the three hottest readings with their minutes.

Hint: give the threshold to the lambda by copy: [esik](const Olcum& o) { ... }. For the average, divide the result of accumulate by v.size(). Sorting destroys the vector's original order, so run find_if before sorting.

Solution

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

struct Olcum {
    int dakika;
    double sicaklik;
};

int main() {
    std::vector<Olcum> v = {{0, 22.5}, {5, 23.0}, {10, 21.5},
                            {15, 24.0}, {20, 22.0}, {25, 25.5}};
    const double esik = 23.5;

    auto ilk = std::find_if(v.begin(), v.end(),
                            [esik](const Olcum& o) { return o.sicaklik > esik; });
    if (ilk != v.end()) {
        std::cout << "Ilk asim: dakika " << ilk->dakika << '\n';
    }

    double toplam = std::accumulate(v.begin(), v.end(), 0.0,
                        [](double t, const Olcum& o) { return t + o.sicaklik; });
    std::cout << "Ortalama: " << toplam / v.size() << '\n';

    std::sort(v.begin(), v.end(),
              [](const Olcum& a, const Olcum& b) { return a.sicaklik > b.sicaklik; });
    std::cout << "En sicak 3:";
    for (std::size_t i = 0; i < 3 && i < v.size(); ++i) {
        std::cout << ' ' << v[i].sicaklik << " (dk " << v[i].dakika << ")";
    }
    std::cout << '\n';
    return 0;
}
Ilk asim: dakika 15
Ortalama: 23.0833
En sicak 3: 25.5 (dk 25) 24 (dk 15) 23 (dk 5)

The total is 138.5; divided by six it gives 23.0833. We also added the i < v.size() condition to the loop so that we do not run past the end of the vector when there are fewer than three readings.

In short, a lambda is the way to tell an algorithm "what to do" right where you call it, and choosing the capture mode deliberately is the key to using it without bugs. In the next lesson we will learn what to do when things go wrong: error handling with exceptions.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. After the lines double esik = 24.0; auto f = [esik](double x) { return x > esik; }; esik = 30.0; what does f(25.0) return?
2. What does std::find_if return if no element satisfies the condition?
3. You want to store different lambdas in the same std::vector. What should the element type be?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.