C++ lambdas and the standard algorithms

The <algorithm> header provides functions that work on ranges given by two iterators: sort, find_if, count_if, transform, accumulate, and more. Many take a predicate or comparison function. A lambda expression writes such a function in place: [capture](parameters) { body }. The capture list copies or references variables from the surrounding scope.

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

void show(const char* label, const std::vector<int>& v) {
  std::cout << label << ":";
  for (int x : v) {
    std::cout << " " << x;
  }
  std::cout << "\n";
}

int main() {
  std::vector<int> v = {5, 2, 8, 1, 9, 3};

  std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
  show("descending", v);

  auto it = std::find_if(v.begin(), v.end(), [](int x) { return x < 4; });
  std::cout << "first below 4: " << *it << "\n";

  int threshold = 4;
  auto above = std::count_if(v.begin(), v.end(), [threshold](int x) { return x > threshold; });
  std::cout << "above " << threshold << ": " << above << "\n";

  std::vector<int> squares(v.size());
  std::transform(v.begin(), v.end(), squares.begin(), [](int x) { return x * x; });
  std::cout << "sum of squares: " << std::accumulate(squares.begin(), squares.end(), 0) << "\n";

  v.erase(std::remove_if(v.begin(), v.end(), [](int x) { return x % 2 != 0; }), v.end());
  show("evens only", v);
}
Read the full lesson