A graph is a set of vertices connected by edges, and in C++ the usual implementation is an adjacency list: a std::vector<std::vector<int>> where adj[u] holds the neighbours of vertex u. The standard library supplies everything you need for traversal (std::queue, std::vector) and for weighted shortest paths (std::priority_queue).
This article builds a small Graph class with C++20, then implements breadth-first search, depth-first search and Dijkstra's algorithm, and compares the adjacency list to an adjacency matrix.
| Property | Adjacency list | Adjacency matrix |
|---|---|---|
| Memory | O(V + E) | O(V^2) |
| Edge lookup (u, v) | O(degree of u) | O(1) |
| Iterate neighbours of u | O(degree of u) | O(V) |
| Best for | Sparse graphs | Dense graphs, small V |
A matrix in C++ is std::vector<std::vector<int>> m(V, std::vector<int>(V, 0)), with m[u][v] = 1 for an edge. Most real graphs (road networks, social graphs, dependency graphs) are sparse, so the list is the default choice and the one used below.
For weighted graphs, store each neighbour as a pair of target and weight. An unweighted graph can use weight 1 and share the same class.
There is no manual memory management: the vectors free themselves, which removes the leak risk of a hand-written linked-list graph. Vertices are numbered 0 to size() - 1; if your nodes are strings, keep a std::unordered_map<std::string, std::size_t> that maps names to indices.
BFS visits vertices in increasing distance (number of edges) from the start and finds shortest paths in unweighted graphs. It returns the distance to every vertex, with -1 for unreachable ones.
Time is O(V + E). The structured binding [v, w] unpacks each edge; w is unused here, so compilers may warn, and you can write [v, _] style names or access edge.to directly if your warning flags are strict.
DFS follows a path as deep as possible, then backtracks. A recursive lambda keeps the visit order in a result vector. For very deep graphs, replace recursion with an explicit std::stack to avoid stack overflow.
DFS also drives cycle detection, topological sorting of directed acyclic graphs and finding connected components.
For non-negative weights, Dijkstra's algorithm uses a min-heap so the closest unfinished vertex is always processed next. It runs in O((V + E) log V).
Join the snippets in one file and build with g++ -std=c++20 -O2 -Wall -Wextra graph.cpp -o graph. The output is:
Dijkstra requires non-negative weights. For graphs with negative edges use Bellman-Ford instead.
Create the Graph with directed = true, so add_edge inserts only u -> v. Everything else, including traversals, works unchanged.
No. You build one from std::vector and friends, or use the Boost Graph Library when you need a ready-made, generic solution.
Use BFS to find shortest paths in unweighted graphs and for level-order exploration. Use DFS for cycle detection, topological sort and exhaustive search.
Map each name to an integer index with std::unordered_map, store the reverse names in a vector, and run algorithms on the integer indices.
In C++ a graph is naturally a std::vector of neighbour lists, which uses O(V + E) memory and cleans up automatically. BFS with std::queue gives unweighted shortest paths, DFS with recursion or std::stack supports ordering and cycle problems, and Dijkstra with std::priority_queue handles non-negative weights. Pick a matrix only for small, dense graphs.