The C++ Standard Library (C++ Core #10)
The standard library is a set of containers, iterators, and algorithms with documented complexity. The exam questions are usually “which container”, “what does this algorithm return”, and “which iterators does this operation invalidate”. The DSA series covers usage patterns; this post covers the guarantees.
Containers at a glance
| Container | Structure | Access | Insert/erase | Find |
|---|---|---|---|---|
vector |
contiguous array | \(O(1)\) | \(O(1)\) back, \(O(n)\) middle | \(O(n)\) |
deque |
segmented array | \(O(1)\) | \(O(1)\) both ends | \(O(n)\) |
list |
doubly linked nodes | \(O(n)\) | \(O(1)\) with iterator | \(O(n)\) |
forward_list |
singly linked nodes | \(O(n)\) | \(O(1)\) after iterator | \(O(n)\) |
set / map |
red-black tree | \(O(\log n)\) | \(O(\log n)\) | \(O(\log n)\) |
unordered_set / map |
hash table | avg \(O(1)\) | avg \(O(1)\) | avg \(O(1)\) |
stack / queue |
adapter | \(O(1)\) ends | \(O(1)\) | — |
priority_queue |
binary heap | \(O(1)\) top | \(O(\log n)\) | — |
Two facts the table hides: a vector scan is much faster than a list scan
because of cache locality, and node-based containers pay an allocation per
element.
std::vector<int> v = {3, 1, 4};
v.push_back(1); // amortized O(1)
v.insert(v.begin(), 2); // O(n), shifts everything
std::sort(v.begin(), v.end()); // O(n log n)
std::map<std::string,int> m;
m["a"] = 1; // O(log n)
m.find("a"); // O(log n)
std::array<int, N> is a fixed-size container with no heap allocation; use it
when the size is a compile-time constant.
std::list rarely the right choice even though itsinsert/erase are \(O(1)\)?
ASolution
Finding the position is \(O(n)\), every node is a separate allocation, and the
nodes are scattered in memory, so each step is a cache miss. A vector with
bulk operations is usually faster.
Iterators and invalidation
Iterators generalize pointers. Categories decide which algorithms accept them:
| Category | Operations | Containers |
|---|---|---|
| Input/Output | single pass, ++, * |
streams, inserters |
| Forward | multi-pass ++ |
forward_list, unordered_* |
| Bidirectional | ++, -- |
list, set, map |
| Random access | +, -, [], < |
vector, deque, array |
| Contiguous (C++20) | random access + contiguous storage | vector, array, string |
std::sort needs random access. std::list has a member sort(); std::set is
already ordered.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.55cm, minimum height=0.5cm, font=\scriptsize}]
\foreach \i in {0,...,5} \node[c, fill=blue!10] at (\i*0.6,1.3) {};
\node[font=\scriptsize, anchor=east] at (-0.3,1.3) {vector:};
\node[font=\scriptsize, anchor=west] at (3.9,1.3) {one block, cache-friendly};
\foreach \i/\x in {0/0,1/1.4,2/2.8,3/4.2} \node[c, fill=orange!18] at (\x,0) {};
\foreach \i/\x in {0/0,1/1.4,2/2.8,3/4.2} {
\draw[->, thick] (\x+0.3,0) -- (\x+1.05,0);
}
\node[font=\scriptsize, anchor=east] at (-0.3,0) {list:};
\node[font=\scriptsize, anchor=west] at (5.4,0) {a node and a pointer per element};
\end{tikzpicture}
Invalidation is the exam favourite:
| Container | Invalidated by |
|---|---|
vector |
reallocation invalidates everything; otherwise only at/after the insertion point |
deque |
push/pop at either end invalidates iterators (references survive) |
list, set, map |
only the erased element |
unordered_* |
rehash invalidates iterators (references survive) |
string |
any modification that reallocates (small-string optimization complicates it) |
std::vector<int> v = {1,2,3};
for (auto it = v.begin(); it != v.end(); ) {
if (*it % 2 == 0) it = v.erase(it); // erase returns the next iterator
else ++it;
}
v.erase(it) invalidates it, so ++it in the loop header is use-after-free.
For “remove all matching”, std::erase (C++20) or the erase-remove idiom is
simpler:
v.erase(std::remove_if(v.begin(), v.end(),
[](int x){ return x % 2 == 0; }), v.end());
for (auto x : v) v.push_back(x); a bug?ASolution
push_back may reallocate, which invalidates the iterators the range-for is
using, and the loop may also never terminate because the container keeps
growing. Iterate over a copy or index.
Algorithms
The algorithms live in <algorithm> and <numeric> and work through iterators.
They do not know about containers.
std::sort(v.begin(), v.end()); // O(n log n)
std::stable_sort(v.begin(), v.end()); // preserves equal elements
std::reverse(v.begin(), v.end()); // O(n)
std::find(v.begin(), v.end(), 42); // O(n), returns iterator
std::count(v.begin(), v.end(), 7); // O(n)
std::lower_bound(v.begin(), v.end(), 5); // O(log n), sorted input
std::upper_bound(v.begin(), v.end(), 5); // first > 5
std::binary_search(v.begin(), v.end(), 5); // bool, sorted input
std::min_element(v.begin(), v.end()); // O(n)
std::accumulate(v.begin(), v.end(), 0); // O(n), <numeric>
std::unique(v.begin(), v.end()); // removes adjacent duplicates
std::max(a, b); std::min(a, b); std::swap(a, b);
std::unique does not erase; it moves duplicates to the end and returns the new
logical end. The erase-remove idiom finishes the job. It only removes adjacent
duplicates, so sort first if you want global uniqueness.
std::lower_bound on an unsorted range is undefined behaviour, not just wrong.
std::binary_search calls lower_bound internally and returns only a boolean.
// count elements in [lo, hi]
auto first = std::lower_bound(v.begin(), v.end(), lo);
auto last = std::upper_bound(v.begin(), v.end(), hi);
long long n = last - first;
Complexity summary:
| Algorithm | Complexity |
|---|---|
sort |
\(O(n \log n)\) |
stable_sort |
\(O(n \log n)\) time, \(O(n)\) space |
partial_sort |
\(O(n \log k)\) |
nth_element |
\(O(n)\) average |
find, count, accumulate |
\(O(n)\) |
lower_bound, upper_bound |
\(O(\log n)\) comparisons, random access |
make_heap, sort_heap |
\(O(n)\), \(O(n \log n)\) |
std::unique(v.begin(), v.end()) on {1,1,2,1} — what remains?ASolution
{1,2,1,...}: it removes only adjacent duplicates, so the last 1 survives.
Sort first for global uniqueness.
string and string_view
std::string owns a contiguous, null-terminated buffer. Small strings are stored
inline (small-string optimization), which is why sizeof(std::string) is around 32
bytes and why a short string does not allocate.
std::string s = "hello";
s.size(); // 5
s.c_str(); // const char*, null-terminated, valid until modification
s.substr(1, 3); // "ell", allocates a new string
s.find("ll"); // 2, or npos
s += " world"; // amortized O(1)
std::string_view (C++17) is a non-owning {ptr, length} pair. It avoids
allocations for read-only parameters, but it does not own the characters.
void print(std::string_view sv) { std::cout << sv; }
std::string s = "hello";
print(s); // ok
print("hello"); // ok, no allocation
std::string_view sv = s.substr(1); // dangling: the temporary string is gone
The call print(s.substr(1)) is safe, because the temporary lives until the end
of the full expression. Storing the view is not. A string_view is also not
guaranteed to be null-terminated, so never pass sv.data() to a C function
expecting a C string.
std::string_view sv = "abcdef";
std::string_view part = sv.substr(0, 3); // "abc", no terminator
part.data()[3]; // 'd', not '\0'
std::string_view unsafe as a function parameter?ASolution
When the caller passes a temporary std::string or a substring. The view does
not extend the lifetime, so the characters die at the end of the full expression.
pair and tuple
std::pair is two values; std::tuple is any number. Both compare
lexicographically.
std::pair<int,std::string> p = {1, "one"};
p.first; p.second;
auto t = std::make_tuple(1, 2.5, std::string("x"));
std::get<0>(t); // 1
std::get<double>(t); // 2.5, by type
auto [a, b, c] = t; // structured bindings (C++17)
std::tie creates a tuple of references, which is useful for comparisons and
multiple return values:
int x, y;
std::tie(x, y) = std::make_pair(3, 4);
Structured bindings work with pairs, tuples, arrays, and simple structs.
auto [a, b] = p; preferred over p.first and p.second inloops?
ASolution
It names the fields once, avoids repeated member access, and works the same for
tuples and structs. The copy semantics are explicit through auto& or
const auto&.
optional and variant
std::optional<T> is “a T or nothing”, with no heap allocation. It replaces
out-parameters and sentinel values.
std::optional<int> parse(const std::string& s) {
try { return std::stoi(s); }
catch (...) { return std::nullopt; }
}
auto v = parse("42");
if (v) std::cout << *v;
std::cout << v.value_or(-1);
std::variant<A,B,C> is a type-safe union. It knows which alternative is active.
std::variant<int, std::string> v = 42;
std::holds_alternative<int>(v); // true
std::get<int>(v); // 42; throws bad_variant_access if wrong
std::get_if<std::string>(&v); // nullptr, no exception
std::visit([](auto&& x) { std::cout << x; }, v);
std::monostate is an empty type used as the first alternative when a variant
must be default-constructible.
Both are value types: they store their contents inline and copy/move with the usual rules.
std::get<int> a variant currently holding astd::string?
ASolution
It throws std::bad_variant_access. Use std::get_if or std::visit when the
alternative is not known.
numeric_limits
<limits> gives the properties of arithmetic types without hard-coded constants.
std::numeric_limits<int>::max(); // 2147483647
std::numeric_limits<int>::min(); // -2147483648
std::numeric_limits<double>::epsilon(); // 2.22e-16
std::numeric_limits<double>::infinity();
std::numeric_limits<int>::is_signed; // true
std::numeric_limits<int>::digits; // 31 value bits
std::numeric_limits<int>::is_integer; // true
Use max() instead of INT_MAX in generic code. Note that min() for floating
types is the smallest positive normal value, while lowest() is the most negative
finite value.
constexpr int INF = std::numeric_limits<int>::max();
constexpr long long LINF = std::numeric_limits<long long>::max() / 4; // avoid overflow
numeric_limits<double>::min() andlowest()?
ASolution
min() is the smallest positive normal value; lowest() is the most negative
finite value. For integers they are the same as the usual min/max.
Integer types and fixed-width integers
<cstdint> provides types with guaranteed widths:
int8_t, int16_t, int32_t, int64_t
uint8_t, uint16_t, uint32_t, uint64_t
intptr_t, uintptr_t // hold a pointer
intmax_t, uintmax_t // widest available
Use them for binary formats, hashing, and anything where the width is part of the
contract. Use int/long long for ordinary arithmetic, where the platform’s
natural width is faster.
std::size_t is the unsigned type of sizeof; std::ptrdiff_t is the signed type
of pointer subtraction. Mixing size_t with int is the signed/unsigned trap from
Ch. 6.
std::size_t n = v.size();
for (std::size_t i = 0; i < n; ++i) { } // fine
for (int i = (int)n - 1; i >= 0; --i) { } // fine if n fits in int
std::byte (C++17) is the type for raw bytes, distinct from char and unsigned
char:
std::byte b{0xFF};
int i = std::to_integer<int>(b);
int64_t not always long long?ASolution
It is a typedef for whichever standard type is exactly 64 bits on the platform
(long on LP64 Linux, long long on Windows). Do not assume the underlying type
in overloads or printf format strings.
Bugs and edge cases
- Iterator invalidation.
push_back,erase,insert, and rehash all have rules; the loop that ignores them is the bug. lower_boundon unsorted data. UB, not just a wrong answer.uniquewithout erase. It only moves elements; the container size is unchanged.string_viewof a temporary. Dangling characters.c_str()after modification. The pointer may be stale.operator[]out of range. UB;at()throws.- Comparing
size()with a negativeint. Signed/unsigned conversion. std::endlin a loop. It flushes every iteration; use'\n'.- Assuming
unordered_mapiteration order. It is unspecified and can change after insertion. vector<bool>. Bit-packed,operator[]returns a proxy, notbool&.
lower_bound and keeps elementssorted after insertions. Which one, and what is the cost?
ASolution
std::set or std::map: \(O(\log n)\) insert and lookup, sorted iteration,
lower_bound in \(O(\log n)\). A sorted vector is faster to scan but pays \(O(n)\)
per insertion.
That is the end of the C/C++ series. The next step is practice: predict output on
small programs, compile with -Wall -Wextra -fsanitize=undefined, and read the
standard’s wording for anything that surprises you.