Examples

C++ examples

Build fast applications with modern types and classes.

49 examples

C++ Basics

Write and run a first program.

C++

C++ conditions and range loops

Filter a sequence while accumulating a result.

C++

C++ functions and references

Use a reference parameter to update a caller's value.

C++

C++ recursive factorial

Trace recursive calls and their return values.

C++

C++ strings and string streams

Use std::string, parse text with getline and istringstream, and convert between text and numbers.

C++

C++ references, const, and auto

Pass large objects without copying, protect them with const, and let the compiler deduce types.

C++

C++ lambdas and the standard algorithms

Sort, search, count, transform, and remove elements with algorithms and small anonymous functions.

C++

C++ Classes

Group data and behavior.

C++

C++ constructors and encapsulation

Initialize private state and expose a controlled interface.

C++

C++ abstract classes and virtual dispatch

Invoke derived behavior through a base reference.

C++

C++ composition and RAII

Let owned members manage their resources automatically.

C++

C++ function templates

Reuse one type-checked algorithm for different types.

C++

C++ inheritance and virtual functions

Call the right method through a base-class pointer, and see what slicing does.

C++

C++ operator overloading

Give a Vec2 class natural arithmetic, comparison, and output operators.

C++

C++ smart pointers and ownership

Use unique_ptr for single ownership, shared_ptr for shared ownership, and weak_ptr to observe.

C++

C++ vectors and iterator invalidation

Grow a dynamic array and use checked access.

C++

C++ binary search with lower_bound

Find an insertion position and check whether it is a match.

C++

C++ stack and queue adapters

Compare LIFO and FIFO removal on the same values.

C++

C++ ordered maps and frequencies

Count keys and traverse them in sorted order.

C++

C++ linked lists with unique ownership

Build a node chain with automatic destruction.

C++

C++ sorting: insertion sort, merge sort, and std::stable_sort

Write two sorts by hand and sort records with a comparator, keeping equal items in order.

C++

C++ singly linked list with unique_ptr

Own each node with a unique_ptr, push at the front, reverse the list, and let destructors do the cleanup.

C++

C++ binary search tree traversals

Insert values into a BST and visit them depth-first and level by level.

C++

C++ priority_queue and the top-k pattern

Use a binary heap to get the smallest element quickly, and keep the k largest values of a stream.

C++

C++ graphs: BFS, DFS, and connected components

Store a graph as adjacency lists, visit it breadth-first and depth-first, and count its components.

C++

C++: best, worst, and average case of linear search

Count comparisons to see that one algorithm can have different costs on different inputs.

C++

C++: amortized cost of a growing array

Count the copies made by a doubling array to see why push_back is amortized constant time.

C++

C++: a hash join with unordered_map

Join two tables by building a hash table on one and probing it with each row of the other.

C++

C++: an ordered index with std::map

Answer range and nearest-key queries with lower_bound and upper_bound.

C++

C++: page replacement with FIFO and LRU

Count page faults for two replacement policies and see Belady's anomaly.

C++

C++: protecting shared data with std::mutex

Run two threads that increment one counter and use a lock to keep every update.

C++

C++: the Internet checksum

Compute the 16-bit ones'-complement checksum used by IP, TCP, and UDP, and use it to detect corruption.

C++

C++: forwarding with longest-prefix match

Pick the most specific route that matches a destination address, as a router does.

C++

C++: a small unit-test harness

Check results and expected exceptions with a macro and a template, and report failures.

C++

C++: the observer pattern with std::function

Notify any number of listeners without the publisher knowing what they do.

C++

C++: preventing buffer overflows with bounds checks

Reject writes that do not fit in a buffer and use at() so out-of-range reads fail safely.

C++

C++: validating untrusted input with std::from_chars

Parse a port number strictly and reject anything that is not exactly a number in range.

C++

C++: splitting a sum across std::async tasks

Run two halves of a computation concurrently and combine the results with futures.

C++

C++: lock-free counting with std::atomic

Increment a shared counter from four threads without a mutex.

C++

C++: A* search with a Manhattan-distance heuristic

Guide a shortest-path search with an estimate of the remaining distance.

C++

C++: minimax with alpha-beta pruning

Search a game tree and skip branches that cannot change the result.

C++

C++: entailment by enumerating models

Test whether a knowledge base entails a query by checking every truth assignment.

C++

C++: backward chaining from a goal

Prove a goal by finding a rule that concludes it and then proving that rule's conditions.

C++

C++: linear regression with gradient descent

Fit y = w·x + b by repeatedly moving the parameters against the gradient of the mean squared error.

C++

C++: k-means clustering

Group unlabeled points by alternating between assigning points to centers and moving centers to the mean.

C++

C++: a perceptron learns OR but not XOR

Train the same neuron on two gates and compare the accuracy it can reach.

C++

C++: stable softmax and cross-entropy loss

Turn raw scores into probabilities, measure the loss, and avoid overflow.

C++

C++: convolution with zero padding

Apply a Laplacian kernel so the output has the same size as the input and responds to a single bright pixel.

C++

C++: grayscale conversion and thresholding

Convert color pixels to brightness with luminance weights and split them into foreground and background.

C++