C++C++

C++: More snippets – code examples

Contents

if / else if / else

Control flow#if#condition#elseCompare in all languages
Use case: React differently depending on the case, e.g. compute grades or price tiers.
#include <iostream>

int main() {
    int punkte = 73;
    if (punkte >= 90)      std::cout << "very good\n";
    else if (punkte >= 70) std::cout << "good\n";
    else                   std::cout << "needs improvement\n";
}

The condition goes in parentheses. For a single statement, curly braces are optional – teams usually recommend them anyway.

for loops

Control flow#for#loop#range-forCompare in all languages
Use case: Process every element of a container or repeat n times.
#include <iostream>
#include <string>
#include <vector>

int main() {
    for (int i = 0; i < 3; ++i)
        std::cout << "Round " << i << '\n';
    std::vector<std::string> fruechte{"Apple", "Pear"};
    for (const auto& f : fruechte)
        std::cout << f << '\n';
}

The classic for loop counts, the range-for loop iterates directly over the container. const auto& avoids copies.

Function with default argument

Functions#function#return#default argument#const-refCompare in all languages
Use case: Bundle recurring logic, e.g. greeting texts or calculations.
#include <iostream>
#include <string>

std::string begruesse(const std::string& name, const std::string& gruss = "Hello") {
    return gruss + ", " + name + "!";
}

int main() {
    std::cout << begruesse("Ada") << '\n';
    std::cout << begruesse("Linus", "Hey") << '\n';
}

C++ has no named arguments; default values go at the end of the parameter list. Strings are passed by const& to save copies.

Lambda and capture

Functions#lambda#capture#closure
Use case: Pass small functions inline, e.g. as a comparison, filter or callback.
#include <iostream>

int main() {
    int zaehler = 0;
    auto inkrement = [&zaehler] { ++zaehler; };   // by reference
    inkrement();
    inkrement();

    int start = 100;
    auto addiere = [start](int x) { return start + x; };   // by copy
    start = 0;   // has no effect on the lambda
    std::cout << zaehler << ' ' << addiere(5) << '\n';   // 2 105
}

[&zaehler] accesses the original variable, [start] stores a copy at the time of creation. Reference captures must not outlive the variables.

Inheritance with virtual

OOP#class#struct#inheritance#virtual#override#oopCompare in all languages
Use case: A common interface for different types, e.g. shapes, animals, plugins.
#include <iostream>
#include <string>
struct Tier {
    std::string name;
    virtual ~Tier() = default;
    virtual std::string sprich() const { return name + " makes a sound"; }
};
struct Hund : Tier {
    std::string sprich() const override { return name + " says Woof!"; }
};
int main() {
    Hund h; h.name = "Rex";
    const Tier& t = h;   // access via the base: virtual selects Hund::sprich
    std::cout << t.sprich() << '\n';
}

struct is a class with public members. virtual + override enable polymorphism; via the base reference, Hund::sprich is called. The virtual destructor is mandatory for base classes.

try / catch

Error handling#try#catch#exception#raiiCompare in all languages
Use case: Guard user input or conversions without the program crashing.
#include <iostream>
#include <stdexcept>
#include <string>

int main() {
    try {
        int zahl = std::stoi("abc");
        std::cout << zahl << '\n';
    } catch (const std::invalid_argument& e) {
        std::cout << "Invalid: " << e.what() << '\n';
    }   // there is no finally: cleanup is handled by RAII
}

You catch exceptions by const&. C++ has no finally; instead, destructors (RAII) clean up automatically when the block is left.

Writing and reading a file

Files#fstream#file#getline#raiiCompare in all languages
Use case: Save and load logs, configurations or text data.
#include <fstream>
#include <iostream>
#include <string>

int main() {
    { std::ofstream out("notizen.txt"); out << "Line 1\nLine 2\n"; }
    std::ifstream in("notizen.txt");
    std::string zeile;
    while (std::getline(in, zeile))
        std::cout << zeile << '\n';
}

The block closes out automatically when left (RAII); only then is the file completely written. getline in the while condition reads line by line until the end of the file.

Listing a directory

Files#filesystem#directory#path#c++17
Use case: Find all files in a folder, e.g. for batch processing or backups.
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    for (const auto& eintrag : fs::directory_iterator(".")) {
        std::cout << eintrag.path().filename().string()
                  << (eintrag.is_directory() ? "/" : "") << '\n';
    }
}

<filesystem> (C++17) provides path, directory_iterator, exists, create_directories etc. in a platform-independent way. With some older GCC versions, -lstdc++fs is needed.

unique_ptr and RAII

Memory#unique_ptr#raii#make_unique#memory
Use case: Manage heap objects without memory leaks, e.g. resources, nodes, plugins.
#include <iostream>
#include <memory>

struct Ressource {
    Ressource()  { std::cout << "acquire\n"; }
    ~Ressource() { std::cout << "release\n"; }
};

int main() {
    auto r = std::make_unique<Ressource>();
    std::cout << "working...\n";
}   // release happens automatically, even on return or exception

make_unique creates the object, the destructor of the unique_ptr deletes it. Output: acquire, working..., release. No delete needed.

shared_ptr with reference counter

Memory#shared_ptr#use_count#reference counting
Use case: Share an object among several equal owners, e.g. caches, configurations.
#include <iostream>
#include <memory>
#include <string>

int main() {
    auto konfig = std::make_shared<std::string>("debug=1");
    auto a = konfig;
    auto b = konfig;
    std::cout << konfig.use_count() << '\n';   // 3
    a.reset();
    std::cout << konfig.use_count() << ' ' << *b << '\n';   // 2 debug=1
}

Each owner increases the counter, reset decreases it. At 0, the object is destroyed. Use shared_ptr only for genuinely shared ownership, otherwise unique_ptr.

Function template

Templates#template#generic#max_element
Use case: Write an algorithm for many types without duplicating code.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

template <typename T>
T groesstes(const std::vector<T>& v) { return *std::max_element(v.begin(), v.end()); }

int main() {
    std::cout << groesstes(std::vector<int>{3, 9, 2}) << '\n';
    std::cout << groesstes(std::vector<std::string>{"a", "zz", "b"}) << '\n';
}

The compiler generates a separate function for int and std::string. The type must support operator<. With an empty vector, dereferencing would be UB – in real code, check beforehand.

Concepts for templates

Templates#concepts#requires#c++20#template
Use case: Document template requirements and get understandable error messages.
#include <concepts>
#include <iostream>

template <std::integral T>
T doppelt(T x) { return x * 2; }

template <typename T>
concept Druckbar = requires(T t, std::ostream& os) { os << t; };

template <Druckbar T>
void zeige(const T& t) { std::cout << t << '\n'; }

int main() { std::cout << doppelt(21) << '\n'; zeige("ok"); }

std::integral only allows integers; Druckbar uses requires to check whether os << t is valid. doppelt(2.5) would be rejected with a clear error message.

Threads and std::mutex

Concurrency#thread#mutex#lock_guard#parallel
Use case: Distribute computing work across multiple cores without data races.
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

int main() {
    int zaehler = 0;
    std::mutex m;
    std::vector<std::thread> threads;
    for (int t = 0; t < 4; ++t)
        threads.emplace_back([&] {
            for (int i = 0; i < 1000; ++i) { std::lock_guard<std::mutex> lock(m); ++zaehler; }
        });
    for (auto& th : threads) th.join();
    std::cout << zaehler << '\n';   // 4000
}

lock_guard locks in the constructor and unlocks in the destructor (RAII). Without a mutex, ++zaehler would be a data race (UB). Compile with -pthread. Output: 4000.

std::async and future

Concurrency#async#future#thread
Use case: Start a computation in the background and pick up the result later.
#include <future>
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> v(1000);
    std::iota(v.begin(), v.end(), 1);   // 1..1000
    auto f = std::async(std::launch::async,
                        [&v] { return std::accumulate(v.begin(), v.end(), 0); });
    std::cout << f.get() << '\n';   // 500500
}

std::async starts the task, f.get() waits for the result (and passes on exceptions). Output: 500500. Use -pthread here as well.