C++ std::optional
Find a feasible route without inventing a sentinel duration that overlaps a real answer.
How it works
std::optional<T> either contains a T or is disengaged. It represents ordinary absence well, such as no route fitting a limit. It is not a full error explanation and should not swallow diagnostics that a caller needs. Test presence before using operator*; value throws if disengaged, while value_or supplies an explicit fallback. Returning a small owning optional value avoids references into temporary collections and keeps the helper’s result lifetime independent of its inputs.
Run it locally
Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror optional-results.cpp -o lessonOn Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.
Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.
Example
#include <iostream>
#include <optional>
#include <vector>
std::optional<int> first_feasible(const std::vector<int>& durations, int limit) {
for (int value : durations) { if (value >= 0 && value <= limit) { return value; } }
return std::nullopt;
}
int main() {
std::vector<int> durations{75, 42, 55};
auto result = first_feasible(durations, 60);
if (result) { std::cout << "Feasible: " << *result << " minutes\n"; }
std::cout << "Missing fallback: " << first_feasible(durations, 20).value_or(-1) << '\n';
}
Expected result
Feasible: 42 minutes
Missing fallback: -1
The function returns the first acceptable duration, not the shortest duration. State that selection policy clearly. Minus one is only a presentation fallback here; absence remains explicit inside the interface. In C++23, expected can model value-or-error with a separate error type, but this course baseline does not assume that library facility.
Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.