STL Algorithms and Lambdas

sort, count_if and find_if from <algorithm>, driven by small lambdas that can capture variables.

C++ · beginner · 8 min · 10 steps · free

What you'll learn

algorithms_lambdas.cpp

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {5, 2, 8, 1};
    sort(v.begin(), v.end());                                  // ascending
    sort(v.begin(), v.end(), [](int a, int b) { return a > b; });   // with a lambda: descending
    int evens = count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
    int limit = 4;
    auto big = find_if(v.begin(), v.end(), [limit](int x) { return x < limit; });   // captures limit
    int firstSmall = *big;
    cout << v[0] << " " << evens << " " << firstSmall << endl;
    return 0;
}

Step by step

  1. v is created on the stack with the value [5, 2, 8, 1].
  2. sort puts the vector in ascending order: 1 2 5 8.
  3. A lambda comparator sorts descending: 8 5 2 1.
  4. count_if counts elements where the lambda says true: 8 and 2.
  5. limit is created on the stack with the value 4.
  6. [limit] captures limit into the lambda.
  7. firstSmall is created on the stack with the value 2.
  8. It prints 8 2 2.
  9. The method returns 0.
  10. 8 2 2.

Common mistakes

Best practices

Key takeaways

Check yourself

[](int x){ return x > 0; } captures?

Answer: Nothing. Empty brackets.

Sort descending with?

Answer: A comparator returning a > b. Pass a comparison.

·

More in The Standard Library