C++ code snippets with use cases
32 ready-made code building blocks, sorted by topic.
Basics
- Hello World β A first test of whether the compiler and environment work.
- Variables and types β Store and print values with a fixed type.
- enum class and switch β Name states or options in a type-safe way, e.g. game states or log levels.
Data structures
- Working with std::vector β Manage collections of values: add, sort, sum up.
- std::map β Store mappings, e.g. configurations, counters or lookup tables.
- Sorting with a lambda comparison β Order records by a field, e.g. users by age or products by price.
- Deleting elements from a vector β Remove invalid or unwanted entries from a list.
Strings
- Counting words β Text analysis, e.g. most frequent words in a document or log file.
- Splitting a string at a delimiter β Split CSV lines or paths into parts.
- std::format (C++20) β Format tables, logs and output with width and decimal places.
Advanced
- std::optional instead of magic values β Functions that sometimes have no result (search, parsing), without -1 or nullptr.
- std::variant and std::visit β Store values of several possible types, e.g. JSON values or results of different kinds.
- Moving instead of copying β Pass on large containers or strings without expensive copying.
- Ranges pipeline (C++20) β Filter and reshape data without intermediate containers and nested loops.
- Structured bindings and tuple β Unpack multiple return values or pairs clearly.
Tools
- Measuring runtime β Check how long a piece of code takes (profiling, benchmarks).
- Random numbers β Generate dice rolls, test data, simulations or samples.
- Command-line arguments β Build your own CLI tools that accept parameters.
More snippets
- if / else if / else β React differently depending on the case, e.g. compute grades or price tiers.
- for loops β Process every element of a container or repeat n times.
- Function with default argument β Bundle recurring logic, e.g. greeting texts or calculations.
- Lambda and capture β Pass small functions inline, e.g. as a comparison, filter or callback.
- Inheritance with virtual β A common interface for different types, e.g. shapes, animals, plugins.
- try / catch β Guard user input or conversions without the program crashing.
- Writing and reading a file β Save and load logs, configurations or text data.
- Listing a directory β Find all files in a folder, e.g. for batch processing or backups.
- unique_ptr and RAII β Manage heap objects without memory leaks, e.g. resources, nodes, plugins.
- shared_ptr with reference counter β Share an object among several equal owners, e.g. caches, configurations.
- Function template β Write an algorithm for many types without duplicating code.
- Concepts for templates β Document template requirements and get understandable error messages.
- Threads and std::mutex β Distribute computing work across multiple cores without data races.
- std::async and future β Start a computation in the background and pick up the result later.