Const Pointer Variants and Choosing Between Tree and Hash Maps in C++
Data Structure DesignModel answerLast updated
Explain how const placement changes pointer and pointee mutability in C++, then compare std::map and std::unordered_map on structure, complexity, ordering, key needs and use cases.
Const Pointers and Associative Containers in C++
You are preparing for a C++ language-fundamentals discussion. Two short conceptual questions come up, and each answer should be precise, backed by concrete examples, and ready for follow-up on trade-offs.
Assumptions
- Standard C++ (C++11 or later). Answers should hold for typical standard library implementations such as libstdc++ and libc++.
mapmeansstd::mapandunordered_mapmeansstd::unordered_map.- Interviewers care about the mechanics and the reasoning behind each trade-off, not a memorized one-liner.
Part 1: Const and pointers
Compare the declarations const int* p and int* const p.
- State exactly what cannot change in each case and what you are still free to do.
- Write a short snippet showing which assignments compile and which are rejected.
- Describe a general method for reading such declarations, and apply it to
const int* const p.
Part 2: Ordered vs hash-based maps
Compare std::map and std::unordered_map. Cover:
- the underlying data structure of each,
- the cost of the core operations (lookup, insert, erase, traversal),
- ordering guarantees,
- what each requires of the key type,
- when you would pick one over the other.
What a strong answer includes
- A clear separation between "the pointer" and "the thing pointed to".
- Average and worst-case complexity, with the reason each bound holds.
- At least one practical consideration beyond big-O, such as iterator invalidation or cache behavior.
Hints
Hint 1
A pointer declaration involves two separate objects: the pointer variable and the object it points to. `const` can lock either one, or both. Read the declaration from the variable name outward, to the left.
Hint 2
For the containers, think about what each one stores internally: a balanced tree of nodes versus an array of buckets holding chains. Derive complexity, ordering and key requirements from that structure.
Hint 3
Go beyond big-O: consider worst-case guarantees, hash quality, rehashing and what it invalidates, range queries such as lower_bound, and the cache cost of pointer chasing.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: const int* vs int* const
Core idea
Two things are involved: the pointer (p) and the pointee (*p). const can freeze either or both.
| Declaration | Write through *p | Re-point p | Plain-English reading |
|---|---|---|---|
const int* p (same as int const* p) | no | yes | pointer to a const int |
int* const p | yes | no | const pointer to an int |
const int* const p | no | no | const pointer to a const int |
How to read them
Start at the name and read right to left. const binds to whatever is immediately on its left; if it is the very first token, it binds to what is on its right. So const int* and int const* are identical. Writing int const* keeps the right-to-left rule uniform.
Code
int a = 1, b = 2;
const int* p1 = &a; // pointer to const int
*p1 = 10; // error: cannot write through p1
p1 = &b; // ok: p1 may point elsewhere
int* const p2 = &a; // const pointer; must be initialized here
*p2 = 10; // ok
p2 = &b; // error: p2 itself is const
const int* const p3 = &a;
*p3 = 10; // error
p3 = &b; // error
Subtleties
const int*means read-only through this pointer, not that the int is constant. Ifais non-const,a = 5;still compiles and*p1then reads 5.- Adding const is an implicit, safe conversion (
int*toconst int*). Removing it needsconst_cast, and writing through the result is undefined behavior if the object was originally declaredconst. int* constbehaves much like a reference: bound once, never re-seated.- A const pointer must be initialized at declaration. As a class member, that means the constructor initializer list or a default member initializer.
Part 2: std::map vs std::unordered_map
Data structures
map: a balanced binary search tree, typically red-black. Each element is its own heap node with parent/left/right pointers and a color bit.unordered_map: a hash table with separate chaining. A bucket array is indexed byhash(key) % bucket_count, and elements live in chained nodes.
Complexity
| Operation | map | unordered_map |
|---|---|---|
| find / insert / erase by key | O(log n) guaranteed | O(1) average, O(n) worst |
| full traversal | O(n), sorted | O(n), unspecified order |
lower_bound, range queries | O(log n) | not supported |
Why these hold. Red-black invariants cap tree height at about 2·log₂(n+1), so every operation walks at most that many nodes. For the hash table, O(1) needs two things: a hash that spreads keys fairly evenly, and a bounded load factor. The table rehashes when size() > max_load_factor() * bucket_count() (default max load factor 1.0). Bucket count grows geometrically, so rehash cost is amortized O(1) per insert. If all keys collide, chains grow to length n and operations become O(n).
Constant factors. A map lookup follows about log n pointers, each a likely cache miss. An unordered_map lookup is one hash computation plus a hop or two. Hash tables usually win on point lookups, but for small n, costly hashes (long strings) or heavy collisions, map can be competitive.
Ordering
map iterates in comparator order and offers lower_bound, upper_bound, equal_range, and cheap min/max, which supports predecessor/successor and range queries. unordered_map guarantees no order, and the order can change after a rehash.
Key requirements
map: a comparator (defaultstd::less, usingoperator<) that is a strict weak ordering. Two keys are equivalent when neither is less than the other. A broken comparator (for example one using<=) causes undefined behavior.unordered_map: aHashand aKeyEqual(defaultoperator==) that agree: equal keys must produce equal hashes. Custom struct keys need both a hash functor or specialization and an equality operator.
Invalidation
map: insertion invalidates nothing; erase invalidates only the erased element.unordered_map: a rehash invalidates all iterators, but pointers and references to elements stay valid because nodes do not move. Callreserve(n)up front to avoid surprise rehashes.
Which to choose
Choose map when you need sorted iteration, range or nearest-key queries, a hard worst-case bound (latency-sensitive paths, adversarial input), a key with ordering but no good hash, or iterator stability.
Choose unordered_map when workloads are mostly point lookups, inserts and erases, order does not matter, and a good hash is available: frequency counts, caches, ID-to-object lookups.
If you need both fast lookup and sorted iteration, keep an unordered_map plus a std::set of keys (paying double memory and synchronization), or accept map's O(log n).
Common mistakes
- Claiming
const int*makes the underlying int immutable everywhere. - Mixing up which declaration freezes the pointer and which freezes the pointee.
- Saying
unordered_mapis "always faster" or thatmapis "O(log n) so always slower". - Forgetting that
unordered_maphas an O(n) worst case. - Writing a comparator that is not a strict weak ordering, or a hash inconsistent with equality.
- Assuming rehash invalidates references; it invalidates iterators only.