C++C++

C++: Fortgeschritten – Code-Beispiele

Inhalt

std::optional statt Magic Values

Fortgeschritten#optional#nullopt#c++17
Anwendungsfall: Funktionen, die manchmal kein Ergebnis haben (Suche, Parsing), ohne -1 oder 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';
}

Gibt „ein Wert oder nichts“ typsicher zurück. value_or liefert einen Ersatzwert, has_value()/if (opt) prüft, *opt liest. Ausgabe: 36 -1.

std::variant und std::visit

Fortgeschritten#variant#visit#union
Anwendungsfall: Werte mehrerer möglicher Typen speichern, z. B. JSON-Werte oder Ergebnisse verschiedener Art.
#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("hallo");
    std::visit([](const auto& x) { std::cout << x << '\n'; }, wert);
    std::cout << wert.index() << '\n';   // 2 (dritte Alternative)
}

Eine typsichere Union: Es ist immer genau ein Typ aktiv. std::visit ruft das Lambda mit dem aktiven Wert auf. Ausgabe: 3.14, hallo, 2.

Verschieben statt kopieren

Fortgeschritten#move#rvalue#performance
Anwendungsfall: Große Container oder Strings ohne teures Kopieren weitergeben.
#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);   // Zeiger wechseln, keine Elemente kopiert
    std::cout << b.size() << '\n';               // 3
    a = {"neu"};   // a darf nach dem Move nur zugewiesen oder zerstoert werden
    std::cout << a.size() << '\n';               // 1
}

std::move erlaubt dem Ziel, den Inhalt zu übernehmen. Danach ist die Quelle gültig, aber unspezifiziert – neu zuweisen ist erlaubt, alten Inhalt lesen nicht.

Ranges-Pipeline (C++20)

Fortgeschritten#ranges#views#filter#transform#c++20
Anwendungsfall: Daten filtern und umformen, ohne Zwischen-Container und verschachtelte Schleifen.
#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 sind lazy: Erst beim Durchlaufen wird gefiltert und transformiert; es entsteht kein neuer Vektor. Die View darf ihren Quell-Container nicht überleben.

Structured Bindings und tuple

Fortgeschritten#structured-binding#tuple#pair#c++17
Anwendungsfall: Mehrere Rückgabewerte oder Paare übersichtlich auspacken.
#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 + "wurde eingefuegt?"
    std::cout << std::boolalpha << neu << ' ' << it->first << '\n';
}

auto [a, b, c] = ... zerlegt Tupel, Paare, Arrays und einfache structs. emplace liefert ein Paar aus Iterator und einem bool zurück. Ausgabe: Ada 36 1.68 / true Ada.