Algorithms and Ranges

Algorithms and Ranges

Searching, sorting, transforming, and filtering with the STL and modern ranges.

Algorithms and Ranges

Common algorithms

std::sort(values.begin(), values.end());
auto it = std::find(values.begin(), values.end(), 42);
int count = std::count(values.begin(), values.end(), 0);
std::reverse(values.begin(), values.end());

Transform and copy

std::vector<int> doubled(values.size());
std::transform(values.begin(), values.end(), doubled.begin(),
               [](int x) { return x * 2; });

Predicates

bool any_negative = std::any_of(values.begin(), values.end(),
                                [](int x) { return x < 0; });

C++20 ranges

namespace views = std::views;
auto even_squares = values
    | views::filter([](int x) { return x % 2 == 0; })
    | views::transform([](int x) { return x * x; });

Important ideas

Best-practice reminders

Common ranges algorithms

auto pos = std::ranges::find(values, 42);
std::ranges::sort(values);
auto sum = std::accumulate(values.begin(), values.end(), 0);

Projections

struct User { std::string name; int score; };

std::ranges::sort(users, std::greater<>{}, &User::score);

Lazy views vs materialized results

auto active_names = users
    | std::views::filter([](const User& user) { return user.score > 0; })
    | std::views::transform([](const User& user) { return user.name; });