Search⌘ K
AI Features

Solution: The Mixed Data Logger

Explore how to use C++ variants to store mixed data types safely and apply lambdas with standard algorithms like count_if. Understand checking variant types with holds_alternative and retrieving values with get. This lesson helps you implement a robust mixed data logger demonstrating modern C++ type safety and functional programming techniques.

We'll cover the following...
C++ 23
#include <iostream>
#include <vector>
#include <variant>
#include <algorithm>
#include <string>
using LogEntry = std::variant<int, std::string>;
int main() {
std::vector<LogEntry> logs = { 200, "System OK", 404, 500, "User Login" };
int criticalErrors = std::count_if(logs.begin(), logs.end(), [](const LogEntry& entry) {
// Check if the entry is currently holding an integer
if (std::holds_alternative<int>(entry)) {
// Safely extract the integer and check the condition
return std::get<int>(entry) > 400;
}
// If it's a string, it's not an error code
return false;
});
std::cout << "Critical errors found: " << criticalErrors << "\n";
return 0;
}
...