CodeBlanks Logo Icon CodeBlanks

Lambdas with STL

Learn to use lambdas with STL algorithms.

Lambdas with STL

STL algorithms often take a lambda. By passing a lambda as the third parameter to std::sort you get custom comparison. Example: std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); sorts descending.

std::find_if and std::count_if also use lambdas. std::find_if returns the first element matching a condition, std::count_if returns the count of matching elements. Example: std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }) counts even numbers. Lambdas make these algorithms very powerful; no separate function is needed.

find_if and count_if

std::find_if finds the first element matching a condition. The condition is a lambda returning bool: std::find_if(v.begin(), v.end(), [](int x) { return x > 10; }). If the returned iterator equals v.end() nothing was found.

std::count_if gives the count of elements matching a condition. For example std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }) returns the number of even values. These two algorithms are the most common ways to pass lambdas to STL. Thanks to lambdas the condition is written at the call site; no separate function is needed.

Practice Sort descending with a lambda

Sort v = {3, 1, 4, 1, 5} in descending order with std::sort. Pass the lambda [](int a, int b) { return a > b; } as the third parameter. Print the result in a for loop with spaces.

Starter code

main.cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5};
    // Sort descending with a lambda passed to std::sort, print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5};
    std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
    for (int x : v) {
        std::cout << x << " ";
    }
    return 0;
}

Expected output

5 4 3 1 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which STL algorithm sorts with a lambda comparator?

main.cpp
std::sort(v.begin(), v.end(), [](int a, int b) { ... });
  • std::sort Correct answer
  • std::find
  • std::count
  • std::accumulate

Explanation: std::sort sorts with a custom lambda.

2 Descending sort lambda

Question
std::sort(v.begin(), v.end(), [](int a, int b) { return a ____ b; });
Answer
std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });

Explanation: Write >: return a > b; sorts large to small.

3 Match each algorithm to its use

Term Meaning
std::sort + lambda Custom sort
std::find_if + lambda Search by condition
std::count_if + lambda Count by condition
[](int x) { return x % 2 == 0; } Even number condition

All lessons in Intermediate