C++C++

C++: Advanced – code examples

Contents

std::optional instead of magic values

Advanced#optional#nullopt#c++17
Use case: Functions that sometimes have no result (search, parsing), without -1 or nullptr.
#include <iostream>
#include <map>
#include <optional>
#include <string>

std::optional<int> finde_alter(const std::map<std::string, int>& m, const std::string& name) {
    if (auto it = m.find(name); it != m.end()) return it->second;
    return std::nullopt;
}

int main() {
    std::map<std::string, int> m{{"Ada", 36}};
    std::cout << finde_alter(m, "Ada").value_or(-1) << ' ' << finde_alter(m, "Bob").value_or(-1) << '\n';
}

Returns "a value or nothing" in a type-safe way. value_or yields a fallback value, has_value()/if (opt) checks, *opt reads. Output: 36 -1.

std::variant and std::visit

Advanced#variant#visit#union
Use case: Store values of several possible types, e.g. JSON values or results of different kinds.
#include <iostream>
#include <string>
#include <variant>

int main() {
    std::variant<int, double, std::string> wert = 3.14;
    std::visit([](const auto& x) { std::cout << x << '\n'; }, wert);
    wert = std::string("hello");
    std::visit([](const auto& x) { std::cout << x << '\n'; }, wert);
    std::cout << wert.index() << '\n';   // 2 (third alternative)
}

A type-safe union: exactly one type is active at any time. std::visit calls the lambda with the active value. Output: 3.14, hello, 2.

Moving instead of copying

Advanced#move#rvalue#performance
Use case: Pass on large containers or strings without expensive copying.
#include <iostream>
#include <string>
#include <utility>
#include <vector>

int main() {
    std::vector<std::string> a{"x", "y", "z"};
    std::vector<std::string> b = std::move(a);   // pointers change, no elements copied
    std::cout << b.size() << '\n';               // 3
    a = {"new"};   // after the move, a may only be assigned to or destroyed
    std::cout << a.size() << '\n';               // 1
}

std::move allows the target to take over the contents. Afterwards the source is valid but unspecified – assigning anew is allowed, reading the old contents is not.

Ranges pipeline (C++20)

Advanced#ranges#views#filter#transform#c++20
Use case: Filter and reshape data without intermediate containers and nested loops.
#include <iostream>
#include <ranges>
#include <vector>

int main() {
    std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8};
    auto ergebnis = v | std::views::filter([](int x) { return x % 2 == 0; })
                      | std::views::transform([](int x) { return x * x; });
    for (int x : ergebnis) std::cout << x << ' ';   // 4 16 36 64
    std::cout << '\n';
}

Views are lazy: filtering and transforming happen only during iteration; no new vector is created. The view must not outlive its source container.

Structured bindings and tuple

Advanced#structured-binding#tuple#pair#c++17
Use case: Unpack multiple return values or pairs clearly.
#include <iostream>
#include <map>
#include <string>
#include <tuple>

int main() {
    std::tuple<std::string, int, double> t{"Ada", 36, 1.68};
    auto [name, alter, groesse] = t;
    std::cout << name << ' ' << alter << ' ' << groesse << '\n';

    std::map<std::string, int> m;
    auto [it, neu] = m.emplace("Ada", 36);   // iterator + "was it inserted?"
    std::cout << std::boolalpha << neu << ' ' << it->first << '\n';
}

auto [a, b, c] = ... decomposes tuples, pairs, arrays and simple structs. emplace returns a pair of an iterator and a bool. Output: Ada 36 1.68 / true Ada.