Tsallaka zuwa abun ciki
Justice Tech School

pair, tuple, optional and variant

pair and tuple group values, optional holds a value or nothing and variant holds one of several types. They replace many out parameters.

Example
#include <iostream>
#include <optional>
#include <tuple>
#include <variant>
#include <string>
using namespace std;
optional<int> find_even(int a, int b) { if (a % 2 == 0) return a; if (b % 2 == 0) return b; return nullopt; }
int main() {
    tuple<string, int, double> t{"Ada", 21, 1.7};
    cout << get<0>(t) << get<1>(t) << "\n";
    cout << find_even(3, 4).value_or(-1) << " " << find_even(3, 5).value_or(-1) << "\n";
    variant<int, string> v = "text";
    cout << holds_alternative<string>(v) << "\n";
}

Result

Ada21
4 -1
1

Exercise

Empty optional.

return ;

Quiz Test

What does optional model?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.