Pointer Const-Qualification and C++ Associative Maps
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
During a C++ technical interview focused on language mechanics and standard-library internals (assuming modern C++11 or newer with mainstream STL implementations), address the following two topics with concrete code illustrations and engineering rationale:
-
Pointer
constqualification (const int*vs.int* const):- Contrast
const int*andint* const(and extend your explanation toconst int* const). - Specify which entity cannot be modified in each declaration, which operations remain legal, and illustrate with a short snippet contrasting statements that compile against statements rejected by the compiler.
- State a general rule for decoding arbitrary combinations of
constand*in C++ variable declarations.
- Contrast
-
Ordered vs. hash-based associative containers (
std::mapvs.std::unordered_map):- Compare
std::map(<map>) andstd::unordered_map(<unordered_map>) across their internal memory layouts, time complexities for lookup/insertion/removal, key-ordering behavior, and requirements placed on custom key types. - Discuss iterator and reference validity across insertions, and give clear practical guidelines for choosing one container over the other in production workloads.
- Compare
Scope & Expectations
- Clearly separate mutability of the pointer variable itself from mutability of the pointed-to memory location, including initialization rules and type-conversion or alias nuances.
- Ground container complexity and iterator/reference invalidation claims in how standard-library node-based trees and bucket-chained hash tables actually store elements.
- Detail what custom keys must implement for each container (ordering comparator vs. hash functor and equality predicate) and the invariants those functions must satisfy.
- Tie architectural trade-offs—latency tail bounds, range queries, memory overhead, and cache locality—to concrete real-world use cases.
Step-by-step walkthrough
Read pointer declarations from right to left (the star fence)
Every pointer variable in C++ involves two separate pieces of memory: the pointer itself (a variable holding a memory address) and the pointee (the
intobject living at that address):pointer variable pointee object +----------------+ +--------------+ | p : 0x7ffee100 | -------------> | a : 42 | +----------------+ +--------------+ changed by: p = &b changed by: *p = 99Whenever
constand*appear together, two simple rules tell you which box is read-only:constqualifies whatever sits directly to its left (with one exception: whenconstappears at the very start of a declaration with nothing to its left, it qualifies the base type right after it, makingconst int*andint const*identical).- Decode the declaration starting at the identifier and moving toward the left, pronouncing
*as "pointer to":
Declaration Right-to-left reading Shortcut ("*" as a fence) ------------------ -------------------------------------------- --------------------------------- int* p p is a pointer to an int nothing is const const int* p p is a pointer to an int that is const const is LEFT of * -> freezes *p int const* p p is a pointer to a const int (identical!) const is LEFT of * -> freezes *p int* const q q is a const pointer to an int const is RIGHT of * -> freezes q const int* const r r is a const pointer to a const int const on BOTH sides -> freezes bothThink of
*as a fence:conston the left of*protects theint(*p);conston the right of*locks the pointer variable itself (q).Part 1A — const int*: a movable pointer to a read-only int
In
const int* p(equivalentlyint const* p), the pointee is read-only throughp, while the pointerpitself is mutable. You can re-seatpto point at differentintvariables (ornullptr), andpdoes not strictly require an initializer at declaration (though initializing tonullptris good practice so you never dereference garbage):int a = 1, b = 2; const int* p = &a; // OK: int* implicitly converts to const int* int val = *p; // OK: reading through p yields 1 p = &b; // OK: p itself is NOT const, so p now points to b p = nullptr; // OK: p can be re-seated again // *p = 3; // COMPILE ERROR: read-only variable is not assignable // int* raw = p; // COMPILE ERROR: cannot drop const without an explicit castTwo important nuances interviewers love checking:
const int*restricts the access path, not necessarily the underlying object. Above,awas declared as plainint a = 1;, so writinga = 5;directly still compiles — and ifppoints toa, reading*pafterward returns5.- Conversions are one-way for safety. Converting
int*toconst int*is implicit because adding a read-only promise is safe. Strippingconstrequiresconst_cast<int*>(p), and writing through the resulting pointer is legal only if the underlying object was originally non-const (int a = 1;); if it points to a truly constant object (const int c = 7;), writing throughconst_castis undefined behavior.
Part 1B — int* const, const int* const, and the type-alias trap
In
int* const q = &a, the pointer variableqitself is immutable (it holds&afor its entire lifetime and can never point anywhere else), while theintit points to remains mutable through*q. Becauseqcan never be assigned later, the compiler requires an initializer whereqis defined:int a = 1, b = 2; int* const q = &a; // OK: initialized to point to a forever *q = 3; // OK: mutates the pointee; a is now 3 // q = &b; // COMPILE ERROR: cannot assign to variable 'q' with const-qualified type 'int* const' // int* const u; // COMPILE ERROR: default initialization of an object of const type 'int* const' const int c = 7; // int* const bad = &c; // COMPILE ERROR: &c has type const int*, which would let *bad = 9 mutate c! const int* const r = &c; // OK: both pointer and pointee are const // *r = 4; // COMPILE ERROR: pointee is const // r = &a; // COMPILE ERROR: pointer r is constHere is the complete summary table, plus a classic
typedef/usingalias trap:Declaration *ptr = v (write int) ptr = &other (re-seat) Must initialize? -------------------- -------------------- ---------------------- ---------------- int* p Allowed Allowed No (use nullptr) const int* p Compile error Allowed No (use nullptr) int* const q Allowed Compile error Yes const int* const r Compile error Compile error YesWatch out for type aliases (
usingortypedef) of pointer types — aliases are not text macros!constmodifies the aliased type as a whole (the pointer itself), not the pointee inside it:using IntPtr = int*; int a = 1, b = 2; const IntPtr t = &a; // Means `int* const t`, NOT `const int* t`! *t = 9; // OK: a becomes 9 // t = &b; // COMPILE ERROR: t itself is constPart 2A — std::map: an ordered balanced binary search tree
Although the C++ standard specifies complexity and iterator guarantees rather than naming a tree algorithm, every major standard library (
libstdc++,libc++, and MSVC STL) implementsstd::map<Key, T, Compare>as a red-black tree — a self-balancing binary search tree where every key in a node's left subtree is smaller and every key in its right subtree is larger:[ 20 : "twenty" ] (Black) / \ v v [ 10 : "ten" ] (Red) [ 30 : "thirty" ] (Red)- Time complexity:
find,insert,emplace,erase(by key),lower_bound, andupper_boundall run in O(log n) worst-case time. A red-black tree withnnodes has height at most2 * log2(n + 1), so even withn = 1,000,000keys a lookup visits at most ~20–40 nodes. Inserting with an iterator hint right after the insertion spot (m.emplace_hint(next_it, k, v)) runs in amortizedO(1)time. - Ordering and range queries: Iterating from
m.begin()tom.end()always visits keys in ascending order according toCompare(defaultstd::less<Key>, i.e.,operator<). Range and nearest-neighbor queries come built in: with keys{10, 20, 30},m.lower_bound(15)jumps to key20inO(log n)time. - Key requirements:
Comparemust form a strict weak ordering (irreflexive!(a < a), asymmetric, and transitive, with transitive equivalence).std::mapnever callsoperator==; it treats two keysaandbas equivalent whenever!(a < b) && !(b < a). Inside each heap node, the stored pair isstd::pair<const Key, T>so callers cannot mutate a key in place and corrupt the tree order (C++17'sm.extract(it)lets you unlink, rename, and re-insert a node without reallocating memory). - Iterator and reference stability: Inserting new elements never invalidates existing iterators, pointers, or references; erasing an element invalidates only iterators and references to that erased element.
- Time complexity:
Part 2B — std::unordered_map: a bucket-chained hash table
std::unordered_map<Key, T, Hash, KeyEqual>is a hash table with separate chaining (required by the C++ standard's bucket API and pointer/reference validity guarantees). It keeps a contiguous array of bucket pointers, where each non-empty bucket chains heap-allocated element nodes in a linked list:buckets array (bucket_count = 5) [0] ---> nullptr [1] ---> [ (6, "six") ] ---> [ (1, "one") ] ---> nullptr (hash % 5 == 1) [2] ---> nullptr [3] ---> [ (8, "eight") ] -> nullptr (hash % 5 == 3) [4] ---> nullptr- Time complexity and load factor: To look up
key, the map computesHash{}(key), maps it into0 .. bucket_count() - 1, and walks that bucket's chain comparing keys withKeyEqual(defaultoperator==).- Average case:
O(1)forfind,insert, anderase. - Worst case:
O(n)if many keys collide into the same bucket (or during anO(n)rehash, though rehashing is rare enough that insertion stays amortizedO(1)on average). - Load factor:
load_factor() = size() / bucket_count(). When an insertion would pushload_factor()abovemax_load_factor()(default1.0), the table allocates a larger bucket array and re-buckets every node (rehashes). Callingu.reserve(N)pre-allocates enough buckets forNelements to avoid mid-loop rehashes.
- Average case:
- No ordering: Iteration order is unspecified, can change completely on rehash, and does not support
lower_boundor sorted range scans. - Key requirements: Needs both a hash functor (
std::hash<Key>) and equality (operator==) obeying hash-equality consistency: whenevera == b,hash(a) == hash(b)must hold. Standard C++ specializesstd::hashfor numbers, pointers,std::string, andstd::string_view, not forstd::pair,std::tuple, or custom structs — sostd::map<std::pair<int, int>, int>compiles immediately (usingpair::operator<), whereasstd::unordered_mapneeds a custom hasher:
struct PairHash { std::size_t operator()(const std::pair<int, int>& p) const noexcept { std::size_t h1 = std::hash<int>{}(p.first); std::size_t h2 = std::hash<int>{}(p.second); // Mix h1 and h2 asymmetrically so (1, 2) and (2, 1) do not collide at 0. return h1 ^ (h2 + 0x9e3779b97f4a7c15ULL + (h1 << 6) + (h1 >> 2)); } };- Iterator vs. reference stability: Any insert that triggers a rehash invalidates all iterators, whereas references and pointers (
T&,T*,const Key&) to existing elements remain valid because the heap-allocated nodes are simply relinked into the new bucket array without moving in memory! - Shared
operator[]gotcha (both containers): Writingif (counts["foo"] > 0)silently inserts{"foo", 0}when"foo"is missing (and fails to compile on aconstmap). Always usefind,count, or C++20containsfor read-only checks.
- Time complexity and load factor: To look up
Side-by-side comparison and how to choose in practice
Feature std::map std::unordered_map ------------------------ ------------------------------------ --------------------------------------- Underlying structure Balanced BST (red-black tree) Hash table with separate chaining find / insert / erase O(log n) worst-case & average O(1) average, O(n) worst-case Iteration order Sorted ascending by Compare Unspecified; scrambles on rehash Range / nearest queries lower_bound, upper_bound, equal_range Not supported Key type requirements Strict weak ordering (`operator<`) `std::hash<Key>` + `operator==` Invalidated on insert Nothing All iterators if rehash; refs stay valid 64-bit node memory (int) ~40 B / node (3 ptrs + color + pair) 16-24 B / node + 8 B per bucket slot(Note: Both containers allocate one heap node per entry, so pointer chasing makes both less cache-friendly than a sorted
std::vectoror C++23std::flat_mapon read-heavy workloads.)- Choose
std::unordered_mapas your default dictionary when you only need exact-key lookup, insertion, and deletion, keys have a fast well-distributed hash, and average latency matters most (for example: symbol tables, request caches, deduplicating IDs, or counting frequencies). - Choose
std::mapwhen you need sorted traversal, range or floor/ceiling queries (lower_bound/upper_bound, such as an exchange order book by price or scheduled events by timestamp), guaranteedO(log n)worst-case latency (such as untrusted network inputs that could trigger hash collisions), iterators that never break across inserts, or composite keys whereoperator<is trivial compared to maintaining a custom hash.
- Choose
Intuition & how it works
For const with pointers, picture a pointer variable p as a sticky note with a house address written on it, pointing to a house (*p). Writing const to the left of * (const int* p) puts a "Do Not Repaint" rule on the house — you cannot change *p through p, though you can freely erase the sticky note and point p at a different house (p = &b). Writing const to the right of * (int* const q) laminates the sticky note in plastic — q is permanently stuck pointing at that one house (q = &b fails), though you can still repaint the house through *q = 3. For std::map vs std::unordered_map, picture an alphabetized library catalog (std::map, a balanced binary search tree that keeps keys sorted and guarantees O(log n) worst-case lookups and range scans) versus a numbered coat-check rack (std::unordered_map, a hash table that jumps straight to a key's bucket in O(1) average time, at the price of scrambled order and O(n) worst-case pile-ups).
Reading C++ declarations left-to-right misleads beginners into calling const int* a "constant pointer", when it is actually a mutable pointer to a read-only int. Likewise, treating std::unordered_map as strictly superior to std::map misses four practical trade-offs: unordered_map cannot answer sorted or range queries (lower_bound), degrades to O(n) under hash collisions, invalidates iterators whenever an insertion triggers a rehash, and lacks built-in std::hash support for std::pair or custom structs.
Walk through both with tiny concrete examples:
1. Pointers (int a = 10, b = 20): With const int* p = &a;, writing p = &b; compiles (*p now reads 20), whereas *p = 99; fails at compile time. With int* const q = &a;, writing *q = 99; compiles (a becomes 99), whereas q = &b; (or leaving int* const q; uninitialized) fails at compile time.
2. Containers (inserting keys 30, 10, 20): std::map<int, int> balances them into 10 <- 20 -> 30, iterates as 10, 20, 30, and answers lower_bound(15) -> 20 in at most 2 comparisons. std::unordered_map<int, int> hashes each key into a bucket slot for single-probe O(1) exact lookup (find(20)), iterates in an unspecified bucket order that can change after growth, and has no lower_bound.
Key points
- Right-to-left pointer rule: A pointee is the object a pointer points to, and const-correctness means using
constso the compiler prevents unintended mutations.constbinds to what is on its left (or on its right when leftmost), soconst int*(same asint const*) freezes*p,int* constfreezesp(requiring initialization), andconst int* constfreezes both. - Access-path constness:
const int* p = &apromises not to mutateathroughp; ifaitself was declared non-const (int a),a = 5remains valid. std::map(ordered tree): Implemented as a red-black tree (a self-balancing binary search tree with height<= 2 * log2(n + 1)), giving O(log n) worst-casefind/insert/erase, sorted iteration,lower_bound/upper_bound, no iterator invalidation on insert, and requiring a strict weak ordering (operator<where equivalence is!(a < b) && !(b < a)).std::unordered_map(chained hash table): Implemented as a hash table with separate chaining (an array of buckets each holding a linked list of heap nodes), giving O(1) average and O(n) worst-case operations, no key order, and requiring a consistentHash+KeyEqualpair (a == bimplieshash(a) == hash(b)).- Rehash invalidation asymmetry: A load factor is
size() / bucket_count(), and a rehash rebuilds the bucket array when insertion would exceedmax_load_factor(). Rehashing invalidates all iterators into anunordered_map, while pointers and references (T*,T&) to stored elements stay valid because nodes are relinked without reallocating.
Common mistakes
- Calling
const int*a "constant pointer":const int*is a pointer to a constantint(the pointer can move); a constant pointer isint* const. - Expanding pointer
typedef/usingaliases by text substitution: Givenusing IntPtr = int*;, writingconst IntPtr p = &a;producesint* const p(frozen pointer, mutableint), notconst int* p. - Saying "
std::unordered_mapis O(1)" without stating "on average": Poor or adversarial hashes put allnkeys into one bucket, making every lookup and insertionO(n). - Claiming the C++ standard mandates red-black trees by name: The standard mandates logarithmic worst-case bounds, sorted order, and node/iterator stability; red-black trees are the universal implementation choice that satisfies all three.
- Using
map[key]to check membership:operator[]default-constructs and inserts a new entry wheneverkeyis missing (mutating the container and wasting memory); usefind(key) != end()or C++20contains(key)instead. - Writing an inconsistent custom hash or symmetric XOR hash: Ignoring a field in
Hashthatoperator==checks violatesa == b => hash(a) == hash(b)(causingfindto miss keys that are already in the map!), and hashing(x, y)ashash(x) ^ hash(y)makes every(a, a)pair collide in bucket0. - Holding
unordered_mapiterators across insertions: Any insertion that exceedsmax_load_factor() * bucket_count()rehashes and dangles saved iterators; storeT*/ references to elements or callreserve(max_n)up front.
Follow-up questions
- What does
const int* const plock down, how must it be initialized as a local variable versus a class field, and how does a trailingconston a method affectthis?const int* const pis a constant pointer to a constantint, forbidding both re-seating (p = &b) and writing through it (*p = 3). As a local or namespace-scope variable it must be initialized right in its definition; as a non-static class data member it must be initialized in a default member initializer (const int* const p = nullptr;) or in the constructor's member initializer list (Holder(const int* x) : p(x) {}), because assigning inside the constructor{ ... }body is already too late. A trailingconston a member function (int get() const) changes the implicitthispointer fromMyClass* consttoconst MyClass* const, preventing mutation of non-mutabledata members and preventing calls to non-constmember functions — though this constness is shallow (physical/bitwise): if the class holds a raw memberint* buf, inside aconstmethodbufhas typeint* const, sobuf = nullptrfails while*buf = 1still compiles!
struct BufferView {
int size = 0;
mutable int read_calls = 0;
int* data = nullptr;
int first() const {
++read_calls; // OK: `mutable` opts out of const
// ++size; // ERROR: `this` is `const BufferView* const`
if (data) *data = 42; // Compiles! `data` became `int* const`, not `const int*`
return data ? data[0] : 0;
}
};
- When an insertion causes
std::unordered_mapto rehash, which handles break—iterators, pointers, or references—and how doload_factor()andmax_load_factor()govern when that happens? When an insertion triggers a rehash, every existing iterator (and the bucket iteration order) is invalidated, whereas references and pointers (Value&,Value*,const Key&) to existing elements remain valid because C++ requires separate-chaining node storage where existing heap nodes are relinked into the new bucket array rather than copied or moved.load_factor()equalsstatic_cast<float>(size()) / bucket_count(), andmax_load_factor()defaults to1.0f. Insertingkelements is guaranteed by the standard not to rehash (keeping iterators valid) wheneversize() + k < max_load_factor() * bucket_count(); callingreserve(N)pre-sizesbucket_count()to at leastceil(N / max_load_factor())so up toNtotal elements can be inserted with zero rehashes. - How would you design a lookup structure that supports both sorted key traversal and constant-time average point queries, and what are the trade-offs? You have three clean engineering options depending on your read/write mix: (1) Dual structure (
std::map<K, V>+std::unordered_map<K, typename std::map<K, V>::iterator>): exact lookups hit the hash index inO(1)average time, sorted range scans walk thestd::mapdirectly, andmapiterators stay valid across future inserts/erases of other keys, trading roughly2xmemory andO(log n)insert/erase maintenance; (2)std::unordered_map+ sort on demand: keep only the hash table forO(1)average reads/writes, and on rare ordered queries copy keys/pointers into astd::vectorandstd::sortinO(n log n)time; or (3) Sortedstd::vector<std::pair<K, V>>(or C++23std::flat_map): ideal when data is loaded once and queried millions of times, giving contiguous cache-friendly sorted iteration and fastO(log n)std::lower_boundbinary search, at the cost ofO(n)middle insertions.
#include <map>
#include <string>
#include <unordered_map>
struct OrderedFastMap {
std::map<std::string, int> ordered;
std::unordered_map<std::string, std::map<std::string, int>::iterator> index;
void upsert(const std::string& key, int value) {
auto hit = index.find(key);
if (hit != index.end()) {
hit->second->second = value; // O(1) average update via stable map iterator
return;
}
auto [map_it, _] = ordered.emplace(key, value); // O(log n) ordered insert
index.emplace(key, map_it); // map_it never invalidates on later inserts
}
};
- How can crafted inputs force
std::unordered_mapinto linear-time operations, and what mitigations prevent hash-collision attacks? In a hash-flooding (collision DoS) attack, an attacker sendsndistinct keys deliberately chosen to land in the exact same bucket: for example, inlibc++andlibstdc++,std::hash<int>is the identity function (hash(x) == x) and bucket selection ishash % bucket_count(), so sendingnmultiples of the primebucket_count()forces allnnodes into bucket0, degrading each lookup/insert toO(n)andninsertions to1 + 2 + ... + n = O(n^2)total time! Defenses include: (1) supplying a per-process randomly seeded hash functor (mixing a secret 64-bit seed fromstd::random_devicevia SplitMix64 or SipHash so the attacker cannot predict collisions), (2) switching tostd::mapon untrusted user keys for a hardO(log n)worst-case bound, and (3) capping request payload sizes. Other language runtimes build this defense in by default: Rust'sHashMapand Python'sdictuse randomized SipHash / per-process hash seeds, while Java 8+'sHashMapconverts any bucket chain longer than 8 nodes (when table capacity is at least 64) into a balanced red-black tree forO(log n)fallback.
#include <cstdint>
#include <random>
#include <unordered_map>
struct SeededIntHash {
std::uint64_t secret_seed;
std::size_t operator()(std::uint64_t x) const noexcept {
// SplitMix64 finalizer keyed with a per-run random seed defeats predictable bucket modulo.
x += secret_seed + 0x9e3779b97f4a7c15ULL;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
return static_cast<std::size_t>(x ^ (x >> 31));
}
};
std::unordered_map<std::uint64_t, int, SeededIntHash> safe_table(
16, SeededIntHash{std::random_device{}()}
);
Follow-up questions
- What does `const int* const p` lock down, how must it be initialized as a local variable versus a class field, and how does a trailing `const` on a method affect `this`?
- When an insertion causes `std::unordered_map` to rehash, which handles break—iterators, pointers, or references—and how do `load_factor()` and `max_load_factor()` govern when that happens?
- How would you design a lookup structure that supports both sorted key traversal and constant-time average point queries, and what are the trade-offs?
- How can crafted inputs force `std::unordered_map` into linear-time operations, and what mitigations prevent hash-collision attacks?
Similar questions
- Wildcard Word Lookup with a Prefix Tree
- Running Median of an Integer Stream
- Streaming Median Tracker
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
More Trexquant interview questions
- Wildcard Word Lookup with a Prefix Tree Medium
- Running Median of an Integer Stream Medium
- Streaming Median Tracker Medium Pro