On this page
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
report_slow_failuresaccepts any contiguous storage viastd::span<const Sample>without templating the function.views::filterandviews::takeevaluate lazily in a single pass with zero heap allocations.
Linked from
Related notes
- tuts/cpp/stdlib/algorithm_and_ranges/ranges_views Linked here; links to this page; shared tags: #cpp, #prog, #ranges, #tier
- tuts/cpp/tutorials/jthread_work_queue_and_atomics Linked here; links to this page; shared tags: #cpp, #prog, #tier, #tutorial
- tuts/cpp/tutorials/raii_and_rule_of_zero_resource_wrapper Linked here; links to this page; shared tags: #cpp, #prog, #tier, #tutorial
- tuts/cpp/stdlib/containers/span Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/tutorials Linked here; links to this page; shared tags: #cpp, #prog
- tuts/cpp/stdlib/algorithm_and_ranges links to this page; shared tags: #cpp, #prog, #ranges
- tuts/cpp/stdlib/containers/vector Linked here; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/auto shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/casts shared tags: #cpp, #prog, #tier