C/C++ Arena

Step 1 of 6

std::optional

std::optional<T> holds either a T or nothing. It's the honest way to say "this might not have a result", instead of magic values like -1 or nullptr:

std::optional<int> find_score(const std::string& name);

if (auto s = find_score("rain")) {
    std::cout << *s;          // or s.value()
}
int x = find_score("nobody").value_or(0);

Return std::nullopt for "nothing".

Your turn: write std::optional<int> parse_int(const std::string& s) that returns the number for strings made only of digits (with an optional leading -), and std::nullopt otherwise (including the empty string and a lone -).

Next: std::variant and std::visit