C++: More snippets – code examples
if / else if / else
#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
#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
#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
#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
#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
#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
#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
#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
#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 exceptionmake_unique creates the object, the destructor of the unique_ptr deletes it. Output: acquire, working..., release. No delete needed.
Function template
#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
#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
#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
#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.