Lesson 6 of 7
Mini Project Part 9 - Lambda Data Pipeline
Build a functional-style data pipeline using lambdas, `std::optional`, `std::variant`, and STL algorithms. The pipeline: reads `StudentRecord` data, filters/maps/reduces using lambdas passed as template parameters, uses `optional` for missing grades, and uses `variant` for a multi-type result type. This is modern C++ in action.
Lambda Data Pipeline - Filter/Map/Reduce with optional & variant
#include <iostream>
#include <vector>
#include <string>
#include <optional>
#include <variant>
#include <algorithm>
#include <numeric>
#include <functional>
#include <iomanip>
struct Student {
std::string name;
std::optional<double> grade; // optional: may not have a grade yet
std::vector<std::string> courses;
int year;
};
// ── Generic pipeline functions ────────────────────────────────
template<typename T, typename Pred>
std::vector<T> filter(const std::vector<T>& v, Pred pred) {
std::vector<T> result;
std::copy_if(v.begin(), v.end(), std::back_inserter(result), pred);
return result;
}
template<typename T, typename U, typename Func>
std::vector<U> map_vec(const std::vector<T>& v, Func f) {
std::vector<U> result;
std::transform(v.begin(), v.end(), std::back_inserter(result), f);
return result;
}
template<typename T, typename Acc, typename Func>
Acc reduce(const std::vector<T>& v, Acc init, Func f) {
return std::accumulate(v.begin(), v.end(), init, f);
}
// ── Result type using variant ─────────────────────────────────
using StatsResult = std::variant<double, std::string>;
StatsResult compute_average(const std::vector<Student>& students) {
std::vector<double> grades;
for (const auto& s : students) {
if (s.grade) grades.push_back(*s.grade);
}
if (grades.empty()) return std::string{"No grades available"};
double sum = std::accumulate(grades.begin(), grades.end(), 0.0);
return sum / grades.size();
}
int main() {
std::vector<Student> students{
{"Alice", 95.0, {"Math", "CS", "Physics"}, 3},
{"Bob", std::nullopt, {"CS"}, 1},
{"Charlie", 72.5, {"Math", "Chemistry"}, 2},
{"Diana", 88.0, {"CS", "Biology"}, 3},
{"Eve", std::nullopt, {"Art"}, 1},
{"Frank", 55.0, {"Math"}, 4},
};
// ── Filter: year 3+ students with grades ─────────────────
auto senior_graded = filter(students, [](const Student& s) {
return s.year >= 3 && s.grade.has_value();
});
std::cout << "=== Senior students with grades ===
";
for (const auto& s : senior_graded) {
std::cout << std::setw(10) << s.name << " grade=" << *s.grade << "
";
}
// ── Map: extract name + grade pairs ──────────────────────
using NameGrade = std::pair<std::string, double>;
auto graded_only = filter(students, [](const auto& s){ return s.grade.has_value(); });
auto name_grades = map_vec<Student, NameGrade>(graded_only,
[](const Student& s) -> NameGrade {
return {s.name, *s.grade};
});
// ── Sort by grade descending ──────────────────────────────
std::sort(name_grades.begin(), name_grades.end(),
[](const auto& a, const auto& b){ return a.second > b.second; });
std::cout << "
=== Rankings ===
";
for (size_t i = 0; i < name_grades.size(); ++i) {
std::cout << "#" << i+1 << " " << std::setw(10) << name_grades[i].first
<< " " << name_grades[i].second << "
";
}
// ── Reduce: count courses across all students ─────────────
int total_courses = reduce(students, 0, [](int acc, const Student& s) {
return acc + (int)s.courses.size();
});
std::cout << "
Total course enrollments: " << total_courses << "
";
// ── Variant result ────────────────────────────────────────
auto result = compute_average(students);
std::visit([](const auto& v) {
using T = std::decay_t<decltype(v)>;
if constexpr (std::is_same_v<T, double>)
std::cout << "Average grade: " << std::fixed << std::setprecision(2) << v << "
";
else
std::cout << "Stats error: " << v << "
";
}, result);
// ── Lambda pipeline: without grades → alternate message ───
std::vector<Student> empty;
auto empty_result = compute_average(empty);
std::visit([](const auto& v) {
using T = std::decay_t<decltype(v)>;
if constexpr (std::is_same_v<T, std::string>)
std::cout << empty_result.index() == 1 ? "Error: " : "";
std::cout << v;
}, empty_result);
std::cout << "
";
return 0;
}Common Mistakes
- Passing lambda by `std::function` in hot paths - each `std::function` call has virtual-dispatch overhead. For the generic `filter`/`map_vec`/`reduce` pattern, use template parameters (as shown) - the lambda type is deduced at compile time and inlined.
- Not handling the `std::nullopt` case in aggregate operations - computing average across `optional<double>` without checking `has_value()` will skip ungraded students. The `optional` type makes the 'may be absent' case explicit and mandatory to handle.
- Returning a `variant` by value for large values - returning `string` inside a variant involves a copy unless you return with `std::move`. For large variant types, consider `std::unique_ptr` inside the variant.
Tip
Tip
Practice Mini Project Part 9 Lambda Data Pipeline in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Composable Functional Pipelines: In-Place Filtering, Transformation & Threaded Aggregation
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Part 9 Lambda Data Pipeline from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Mini Project Part 9 Lambda Data Pipeline is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- Build a functional-style data pipeline using lambdas, `std::optional`, `std::variant`, and STL algorithms.
- Passing lambda by `std::function` in hot paths - each `std::function` call has virtual-dispatch overhead. For the generic `filter`/`map_vec`/`reduce` pattern, use template parameters (as shown) - the lambda type is deduced at compile time and inlined.
- Not handling the `std::nullopt` case in aggregate operations - computing average across `optional<double>` without checking `has_value()` will skip ungraded students. The `optional` type makes the 'may be absent' case explicit and mandatory to handle.
- Returning a `variant` by value for large values - returning `string` inside a variant involves a copy unless you return with `std::move`. For large variant types, consider `std::unique_ptr` inside the variant.
Finished this lesson?