On this page
  1. Tutorial: Ranges & Span Data Pipeline
  2. Goal
  3. Compile & Run
  4. Complete Pure-STL Example
  5. Key Takeaways

Tutorial: Ranges & Span Data Pipeline

Prev: RAII & Rule-of-Zero Resource Wrapper | Up: tutorials | Next: jthread Work Queue & Atomics
Rel: std::span, std::ranges & std::views, std::vector
Ref: cppreference — Ranges | cppreference — std::span
Tags: #public #prog #cpp #tutorial #ranges #tier/core


Goal

Process a slice of telemetry samples using std::span (accepting std::vector, std::array, or C arrays interchangeably) and a lazy C++20 std::views pipeline with zero intermediate heap allocations.

Compile & Run

clang++ -std=c++20 -O2 -Wall -Wextra ranges_pipeline.cpp -o ranges_pipeline && ./ranges_pipeline

Complete Pure-STL Example

#include <array>
#include <iostream>
#include <ranges>
#include <span>
#include <string_view>
#include <vector>

struct Sample {
    std::string_view service;
    int latency_ms;
    bool ok;
};

void report_slow_failures(std::span<const Sample> samples, int threshold_ms) {
    namespace views = std::views;

    auto slow_errors = samples
        | views::filter([threshold_ms](const Sample& s) {
              return !s.ok && s.latency_ms >= threshold_ms;
          })
        | views::take(5);

    for (const Sample& s : slow_errors) {
        std::cout << s.service << ": " << s.latency_ms << " ms\n";
    }
}

int main() {
    std::vector<Sample> vec{
        {"auth", 15, true},
        {"billing", 420, false},
        {"search", 180, false},
        {"billing", 610, false}
    };

    std::array<Sample, 2> arr{{
        {"edge", 500, false},
        {"edge", 12, true}
    }};

    std::cout << "From vector:\n";
    report_slow_failures(vec, 200);

    std::cout << "From array:\n";
    report_slow_failures(arr, 200);
    return 0;
}

Key Takeaways

Linked from

Related notes