Containers and complexity basics
What you will learn on this page
Section titled “What you will learn on this page”- What the six most common standard containers are each good at.
- How to read Big-O for container operations, and what it leaves out.
- Which operations make existing references, pointers, and iterators into a container invalid.
- How to choose a container from the way the data is used.
Choosing a container is a design decision
Section titled “Choosing a container is a design decision”A container decides more than where data is stored. It decides which questions can be answered quickly (“who has ID M-1003?”, “which names start with Ada?”, “who has waited longest?”), whether the data has an order, and whether code elsewhere may keep a reference into it. So the first question is not “which container is fastest?” but “how will this data be used?”:
- Will it be looked up by position, by key, or only walked through in order?
- Does it need to stay sorted?
- Is it added to at the end, at the front, or anywhere?
- Is its size fixed when the code is written?
- Will other code keep references or pointers to its elements?
Big-O in one paragraph
Section titled “Big-O in one paragraph”Big-O describes how the cost of an operation grows as the container grows, with n the number of elements:
- O(1), constant: the same cost for 10 elements or 10 million.
- O(log n), logarithmic: grows very slowly. Doubling n adds one more step; a million elements need about 20.
- O(n), linear: proportional to the size; doubling n doubles the cost.
- Amortized O(1): usually constant, occasionally much more, but constant
on average over many operations.
std::vector::push_backis the standard example: it sometimes reallocates and moves every element, but rarely enough that the average stays constant. - Average O(1): constant for typical inputs, but O(n) in the worst case. Hash tables are like this.
Big-O hides constant factors. Walking through a std::vector touches memory in
order, which processors handle very efficiently; the node-based containers
(std::map, std::set, std::list, and, in practice, the unordered containers) follow
pointers between separate allocations. For small containers, a plain vector
searched from start to end can beat a map whose Big-O is better. Choose by Big-O
for growth, and measure when speed really matters.
The six containers
Section titled “The six containers”| Container | What it is | Good at | Costly or missing |
|---|---|---|---|
std::vector<T> |
A resizable array, elements next to each other | Index O(1); add or remove at the end amortized O(1); walking | Insert or erase in the middle O(n); find by value O(n) |
std::array<T, N> |
A fixed-size array, size part of the type | Index O(1); no allocation; size known when compiling | Cannot grow or shrink |
std::deque<T> |
A double-ended queue in fixed-size blocks | Add or remove at both ends O(1); index O(1) | Insert in the middle O(n); not one contiguous block |
std::map<K, V> |
Key-value pairs kept sorted by key (a tree) | Find, insert, erase O(log n); ordered walks; range queries | Slower lookups than a hash table; one allocation per node |
std::unordered_map<K, V> |
Key-value pairs in a hash table | Find, insert, erase average O(1) | No order; worst case O(n); needs a hash for the key |
std::set<T> |
Unique values kept sorted (a tree) | “Is it there?” O(log n); unique; ordered | Values cannot be changed in place |
There are companions: std::multimap and std::multiset allow repeated keys,
std::unordered_set is the hash-table set, and std::list is a doubly linked
list, rarely the best choice. The default for “a sequence of things” is
std::vector. Reach for another container when an operation you need often is
one the vector is bad at.
Example: a member index
Section titled “Example: a member index”A library needs to look up members by ID (often), find members whose name starts with some text (sometimes, sorted), and list them in the order they joined. No single container does all three well, so the index uses three, each for one job:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Holds the library's members and answers three questions quickly: who has// this ID, whose name starts with this text, and who joined in what order.// One container owns the members; the other two are indexes that store a// member's position (0, 1, 2, ...) in that vector, not the member itself.// Invariant: by_id_ and by_name_ hold exactly one entry per element of// members_, and every stored position is a valid index into members_.class MemberIndex {public: // Adds a member. Returns false, and changes nothing, if the ID is taken. // Amortized O(1) for the vector, average O(1) for the hash map, and // O(log n) comparisons for the multimap. Takes the Member by value: the // index keeps its own Member, moved in from the parameter. If memory runs // out part-way, it undoes its changes and lets the exception through. bool add(Member member);
// Average O(1). Returns nullptr if there is no such member. The pointer // is valid only until the next call to add(): add may move every member // to a new, bigger block of memory. It is a pointer rather than a // reference so that "not found" can be nullptr; `const` so the caller // can read the member but not change it behind the index's back. [[nodiscard]] const Member* find(const std::string& id) const;
// Members whose name starts with prefix, in name order: O(log n + k) // comparisons for k results, plus copying the k members. Returns copies, // so the result stays valid whatever happens to the index later. // std::string_view is a read-only view of characters, so a caller can // pass "Ada" without a std::string being built for it. [[nodiscard]] std::vector<Member> names_starting_with(std::string_view prefix) const;
// Members in the order they were added. [[nodiscard]] const std::vector<Member>& in_join_order() const noexcept { return members_; }
private: std::vector<Member> members_; // owns; insertion order // A hash table from ID to position: by_id_["M-1003"] would be 2 for the // third member added. No order, but finding one ID is average O(1). std::unordered_map<std::string, std::size_t> by_id_; // id -> position // A sorted tree from name to position. multi: two members may share a // name. The third template argument, std::less<> (with empty brackets), // lets lookups compare a std::string key with a std::string_view // directly, instead of first copying the view into a std::string. std::multimap<std::string, std::size_t, std::less<>> by_name_; // sorted};std::vector<Member>owns the members, in joining order, by value. That makesin_join_orderfree and keeps the members together in memory.std::unordered_map<std::string, std::size_t>maps an ID to the member’s position in the vector, for average O(1) lookup by ID. IDs have no useful order, so a hash table fits.std::multimap<std::string, std::size_t, std::less<>>maps names to positions, kept sorted. Names can repeat, so it is a _multi_map. Sorting is what makes prefix search fast: all names starting with “Ada” sit next to each other.std::less<>lets the map compare itsstd::stringkeys directly with astd::string_viewprefix, without building a temporary string.
The maps store positions, not Member& or Member*. The reason is the most
important rule on this page, and it comes next.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Three steps, one per container: store the member, then index it by ID, then// by name. A step can fail only by throwing, for example when memory runs// out. If push_back throws, the vector is left as it was, so nothing needs// undoing; each map insert is wrapped in a try block that undoes the steps// before it.bool MemberIndex::add(Member member) { // count is 0 or 1 in a map with unique keys: 1 means the ID is taken. // Returning here, before any change, is what "changes nothing" means. if (by_id_.count(member.id) != 0) return false;
// The new member will be the last element, so its position is the // current size: 0 for the first member, 1 for the second, and so on. const std::size_t position = members_.size(); members_.push_back(std::move(member)); // may reallocate: positions survive // A reference to the member just stored. Safe to use below: members_ is // not changed again until pop_back, and pop_back is the last use. const Member& added = members_.back(); // If an insert below throws, undo what came before it, so the // invariant still holds. try { // emplace builds the map entry {ID, position} in place. The ID string // is copied into the map as its key. by_id_.emplace(added.id, position); try { by_name_.emplace(added.name, position); } catch (...) { // catch (...) catches any exception. The name insert failed, so // remove the ID entry, then `throw;` re-throws the same // exception to the outer catch. by_id_.erase(added.id); throw; } } catch (...) { // Reached if either insert failed: remove the member from the vector // too, and pass the exception on to add's caller. members_.pop_back(); throw; } return true;}
const Member* MemberIndex::find(const std::string& id) const { // find returns an iterator: either the entry for id, or end() for "no // such key". (Unlike by_id_[id], it never inserts anything.) const auto found = by_id_.find(id); if (found == by_id_.end()) return nullptr; // found->first is the key (the ID), found->second the stored position. // & takes the address of that element of the vector. return &members_[found->second];}
std::vector<Member> MemberIndex::names_starting_with(std::string_view prefix) const { std::vector<Member> result; // lower_bound finds the first name not less than prefix in O(log n); // names with the prefix follow it in sorted order. for (auto it = by_name_.lower_bound(prefix); it != by_name_.end(); ++it) { // Compare the first prefix.size() characters of this name with the // prefix. (substr on a name shorter than the prefix just gives the // whole name, which then does not match.) The names are sorted, so // the first one that does not match means no later one will: stop. if (std::string_view(it->first).substr(0, prefix.size()) != prefix) break; result.push_back(members_[it->second]); // a copy of the member } return result;}How this code works: MemberIndex::add and names_starting_with
add, when everything works. With the four members from main below,
each add appends to the vector and records the new position in both maps:
| Call | members_ position |
by_id_ gains |
by_name_ gains |
|---|---|---|---|
add({"M-1001", "Ada Lovelace"}) |
0 | M-1001 → 0 |
Ada Lovelace → 0 |
add({"M-1002", "Alan Turing"}) |
1 | M-1002 → 1 |
Alan Turing → 1 |
add({"M-1003", "Grace Hopper"}) |
2 | M-1003 → 2 |
Grace Hopper → 2 |
add({"M-1004", "Ada Yonath"}) |
3 | M-1004 → 3 |
Ada Yonath → 3 |
add({"M-1002", "Someone Else"}) |
none: returns false at the first line |
nothing | nothing |
add, when something throws. The nested try blocks undo exactly the
steps that already happened:
| What throws | Already done | Undone by | Result |
|---|---|---|---|
members_.push_back |
nothing | nothing needed: the vector is unchanged | index as before |
by_id_.emplace |
member stored | outer catch: pop_back |
index as before |
by_name_.emplace |
member stored, ID indexed | inner catch: erase the ID; then outer catch: pop_back |
index as before |
In every row the exception still reaches the caller (in the last two rows,
throw; passes it on),
so a failure is never hidden; it just leaves no half-added member behind.
names_starting_with("Ada"). by_name_ keeps its keys sorted, so it holds
Ada Lovelace, Ada Yonath, Alan Turing, Grace Hopper, in that order.
lower_bound("Ada")jumps, in O(log n), to the first name that is not less than"Ada":Ada Lovelace.- Its first 3 characters are
Ada: copy member 0 (M-1001) into the result. Ada Yonathstarts withAda: copy member 3 (M-1004).Alan Turingstarts withAla, notAda:break. Because the names are sorted, no later name can start withAda, soGrace Hopperis never looked at.
The result is M-1001, M-1004, as the output below shows.
add keeps the three containers in step, which is the class’s invariant. If
inserting into one of the maps throws (for example, out of memory), the
catch blocks undo the earlier steps before passing the exception on, so a
failed add leaves the index as it was. (The Member passed in is consumed
either way, because add takes it by value.) names_starting_with uses
lower_bound, which finds in O(log n) the first name that is not less than the
prefix, and walks forward while names still start with it.
Example: a waitlist
Section titled “Example: a waitlist”A waitlist for a popular book must serve members in arrival order and refuse to add someone twice:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A queue of member IDs for one book: first to join is first to be served,// and nobody can be in the queue twice. Two containers hold the same IDs:// the deque remembers the order, the set answers "already waiting?" fast.// Invariant: queue_ and waiting_ contain the same IDs; no ID appears twice.class Waitlist {public: // O(log n) comparisons. Returns false if the member is already waiting. bool join(const std::string& member_id) { // insert returns a pair: .first points at the element, .second is // true if it was newly added and false if the ID was already there. // So this one call both checks for a duplicate and records the ID. if (!waiting_.insert(member_id).second) return false; try { queue_.push_back(member_id); } catch (...) { // The queue could not grow: take the ID out of the set again so // the two containers still agree, then pass the exception on. waiting_.erase(member_id); throw; } return true; }
// O(log n). Removes and returns the member who has waited longest. // Returns an empty std::optional (std::nullopt) when nobody is waiting. std::optional<std::string> next() { if (queue_.empty()) return std::nullopt; // Move the ID out of the front element instead of copying it. That // leaves the front element moved-from (valid, but with no value to // rely on), which is fine because it is removed on the next line. std::string front = std::move(queue_.front()); queue_.pop_front(); // O(1) at the front: why this is a deque waiting_.erase(front); // keep the set in step with the queue return front; // wrapped in a std::optional on the way out }
[[nodiscard]] bool is_waiting(const std::string& member_id) const { return waiting_.count(member_id) != 0; // O(log n) } [[nodiscard]] std::size_t size() const noexcept { return queue_.size(); }
private: std::deque<std::string> queue_; // arrival order std::set<std::string> waiting_; // fast "already waiting?" check};How this code works: Waitlist, step by step
The calls from main below, and what each container holds afterwards:
| Call | Returns | queue_ (front first) |
waiting_ (sorted) |
|---|---|---|---|
join("M-1004") |
true |
M-1004 | M-1004 |
join("M-1001") |
true |
M-1004, M-1001 | M-1001, M-1004 |
join("M-1004") |
false: insert(...).second is false, nothing else runs |
M-1004, M-1001 | M-1001, M-1004 |
next() |
"M-1004" |
M-1001 | M-1001 |
next() |
"M-1001" |
empty | empty |
next() |
std::nullopt |
empty | empty |
After every call, both containers hold the same IDs: that is the invariant. The deque keeps arrival order (the set would sort M-1001 first, which is wrong for a queue), and the set makes the duplicate check O(log n) instead of a walk through the whole queue.
std::deque fits the queue: members join at the back and leave from the front,
and both ends are O(1). A std::vector would need erase(begin()) to remove the
first member, which moves every other element: O(n). The std::set answers “is
this member already waiting?” in O(log n) instead of searching the queue. The
price of two containers is an invariant to keep: both must hold the same IDs.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
MemberIndex index;// Each {"id", "name"} builds a Member to pass to add.index.add({"M-1001", "Ada Lovelace"});index.add({"M-1002", "Alan Turing"});index.add({"M-1003", "Grace Hopper"});index.add({"M-1004", "Ada Yonath"});// M-1002 is already taken, so this add is refused and returns false.const bool added_again = index.add({"M-1002", "Someone Else"});
// std::boolalpha makes the stream print a bool as true/false, not 1/0.std::cout << "duplicate ID added: " << std::boolalpha << added_again << '\n';// Declares `member` inside the if: the body runs only if the pointer is// not null, and `member` cannot be used outside it by mistake.if (const Member* member = index.find("M-1003")) { std::cout << "M-1003 is " << member->name << '\n';}std::cout << "names starting with \"Ada\":";// names_starting_with returns a temporary vector; the range-for keeps it// alive until the loop ends, so the references are safe.for (const Member& member : index.names_starting_with("Ada")) { std::cout << ' ' << member.id;}std::cout << '\n';
Waitlist waitlist;waitlist.join("M-1004");waitlist.join("M-1001");waitlist.join("M-1004"); // already waiting: ignored// Each pass calls next(). The loop goes on while the optional it returns// holds a value; *next is the ID inside it. When the waitlist is empty,// next() returns std::nullopt, which counts as false, and the loop ends.while (const auto next = waitlist.next()) { std::cout << "next on the waitlist: " << *next << '\n';}duplicate ID added: falseM-1003 is Grace Hoppernames starting with "Ada": M-1001 M-1004next on the waitlist: M-1004next on the waitlist: M-1001Invalidation: when references into a container stop being valid
Section titled “Invalidation: when references into a container stop being valid”A reference, pointer, or iterator to an element is invalidated when the element moves or is destroyed. Using it afterwards has undefined behaviour: it may print the right value, print garbage, or crash. This is the most common way to create a dangling reference with containers.
The classic case is a vector growing:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// A vector with one member. Its capacity (room before it must grow) is// typically exactly 1 here, but the standard does not promise that.std::vector<Member> members{{"M-1001", "Ada Lovelace"}};// `first` is not a copy: it is another name for the element that sits// inside the vector's block of memory.const Member& first = members.front(); // refers into the vector's buffer
members.push_back({"M-1002", "Alan Turing"}); // may reallocate: the // buffer `first` refers to // can be freed here
// If push_back needed more room, it got a new block, put the old member// and the new one in it, and freed the old block. `first` was not told: it// still refers to where the first member USED to be. Reading through it// is undefined behaviour; it may print the name, garbage, or crash.// The fix is to look the member up again after the push_back, or to// store a position (as MemberIndex does) instead of a reference.std::cout << first.name << '\n'; // BUG: undefined behaviour if it didA vector keeps its elements in one block. When push_back needs more room than
the block has (its capacity), the vector allocates a bigger block, moves the
elements there, and frees the old one. first still refers into the freed block.
GCC 11 and Clang 14 compile this without any warning under this site’s flags, and
it may even appear to work, which is why it is compiled to show it but never run.
The rules for the containers on this page:
| Container | Adding elements | Removing elements |
|---|---|---|
std::vector |
If it reallocates: everything invalid. If not: elements at and after the insertion point invalid | Elements at and after the erased one invalid |
std::deque |
At either end: iterators invalid, but references and pointers stay valid. In the middle: everything | At either end: only the erased elements (and end()). In the middle: everything |
std::map, std::set |
Nothing invalidated | Only the erased elements |
std::unordered_map |
If it rehashes: iterators invalid, but references and pointers stay valid | Only the erased elements |
std::array |
Cannot add | Cannot remove |
Ways to stay safe, from most to least common:
- Do not keep references into a container across changes to it. Look the element up again afterwards.
- Store a key or position instead, as
MemberIndexdoes. A position stays correct while elements are only added at the end, and the test below checks it through a thousand additions. It would not survive erasing from the middle: see the requirement change below. - Use
reserve(n)when the final size is known: a vector does not reallocate until it holds more than its capacity. This is fragile as a safety measure, because it depends on nobody adding one more element later. - Choose a container whose rules fit:
std::mapandstd::setnever invalidate other elements, so references into them survive any insertion.
find in MemberIndex returns a const Member*, and its comment says the
pointer is valid only until the next add. A function that hands out references
or pointers into a container must say how long they stay valid.
Testing the choices
Section titled “Testing the choices”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one if// the two differ and prints both. They come from lld_test.hpp.
// Adds members M-0 to M-999, so the vector has to move its members to a// bigger block many times. If the maps stored pointers, they would now// point into freed memory; because they store positions, the first and// last members are still found, and an ID never added is not.LLD_TEST(lookups_survive_many_reallocations) { MemberIndex index; for (int i = 0; i < 1000; ++i) { // std::to_string(7) is "7", so this adds {"M-7", "Member 7"}, etc. LLD_CHECK(index.add({"M-" + std::to_string(i), "Member " + std::to_string(i)})); } // The vector has reallocated many times; positions are still right. // Both pointers are taken after the last add, so they are valid. const Member* first = index.find("M-0"); const Member* last = index.find("M-999"); // Checked before the two lines below dereference them with ->, so a // missing member is reported clearly. LLD_CHECK does not stop the test, // though: if a pointer were null, the next line would still use it. LLD_CHECK(first != nullptr && last != nullptr); LLD_CHECK_EQ(first->name, std::string("Member 0")); LLD_CHECK_EQ(last->name, std::string("Member 999")); LLD_CHECK(index.find("M-1000") == nullptr);}
// Sorted, the names are Ad, Ada (M-1), Ada (M-4), Adams. Searching "Ada"// starts at the first Ada, so "Ad" (shorter, and sorted before it) is not// included, and returns the three names that start with "Ada", in name// order, whatever order they were added in.LLD_TEST(prefix_search_is_sorted_and_exact) { MemberIndex index; index.add({"M-3", "Adams"}); index.add({"M-1", "Ada"}); index.add({"M-2", "Ad"}); index.add({"M-4", "Ada"}); // duplicate names are allowed const auto found = index.names_starting_with("Ada"); LLD_CHECK_EQ(found.size(), std::size_t{3}); LLD_CHECK_EQ(found[0].name, std::string("Ada")); LLD_CHECK_EQ(found[2].name, std::string("Adams")); LLD_CHECK(index.names_starting_with("Zed").empty());}
// A refused add must leave all three containers as they were: still one// member, and the name "Grace" never reached the name index.LLD_TEST(duplicate_ids_change_nothing) { MemberIndex index; LLD_CHECK(index.add({"M-1", "Ada"})); LLD_CHECK(!index.add({"M-1", "Grace"})); LLD_CHECK_EQ(index.in_join_order().size(), std::size_t{1}); LLD_CHECK(index.names_starting_with("Grace").empty());}
// M-2 then M-1 join; M-2's second join is refused. They leave in arrival// order. Once M-2 has left, it may join again, at the back. Comparing// next() with "M-2" is true only if the optional holds exactly "M-2".LLD_TEST(waitlist_is_first_come_first_served_without_duplicates) { Waitlist waitlist; LLD_CHECK(waitlist.join("M-2")); LLD_CHECK(waitlist.join("M-1")); LLD_CHECK(!waitlist.join("M-2")); LLD_CHECK_EQ(waitlist.size(), std::size_t{2}); LLD_CHECK(waitlist.next() == "M-2"); LLD_CHECK(!waitlist.is_waiting("M-2")); LLD_CHECK(waitlist.join("M-2")); // may join again after leaving LLD_CHECK(waitlist.next() == "M-1"); LLD_CHECK(waitlist.next() == "M-2"); LLD_CHECK(!waitlist.next().has_value());}The first test adds a thousand members, forcing the vector to reallocate many times, and checks that lookups still find the right members, which would be unsafe if the map stored pointers: undefined behaviour that might even pass, and that the AddressSanitizer build would be likely to catch. The others pin down the behaviour each container was chosen for: sorted and exact prefix search with repeated names, and first come, first served without duplicates.
Choosing a container
Section titled “Choosing a container”Start from the access pattern:
| If you mostly… | Use |
|---|---|
| keep a sequence and walk it, adding at the end | std::vector |
| have a fixed number of elements known when compiling | std::array |
| add and remove at both ends (a queue) | std::deque (or std::queue, which wraps one) |
| look up by key, and never need the keys in order | std::unordered_map / std::unordered_set |
| need keys in sorted order, ranges, or “first key ≥ x” | std::map / std::set |
| ask “is it there?” about a small or rarely changing group | a sorted std::vector with std::binary_search, or std::set |
Common mistakes
Section titled “Common mistakes”- Keeping a reference, pointer, or iterator across
push_backorinsert. Look it up again, or store a key. - Erasing from a container while walking it with a range-
for. The loop’s iterator is invalidated. Use the iterator thaterasereturns, orstd::erase_if(C++20). map[key]to check whether a key exists.operator[]inserts a default value when the key is missing. Usefind,count, orcontains(C++20).- Using
std::list“because inserting is O(1)”. Finding the place to insert is O(n), and walking a list is slow. Measure before choosing it. - Choosing by Big-O alone for small data. For a handful of elements, a vector is usually simplest and fast.
When a requirement changes
Section titled “When a requirement changes”New requirement: “Members can leave the library, and must then disappear from the index.”
Erasing from the middle of members_ would shift every later member down one
position, so every stored position after it would be wrong. Options:
- Swap and pop: move the last member into the removed member’s slot,
pop_back, and update that one member’s entries in both maps. O(1) for the vector, butin_join_orderno longer preserves joining order. - Store members in a node-based container, such as
std::unordered_map<std::string, Member>keyed by ID, with the name index storing IDs. Erasing one member then invalidates nothing else, at the cost of losing joining order unless it is stored separately (for example, a join number in each member). - Mark members as left instead of erasing them, if the library must keep their history anyway. Positions never change, and lookups filter out former members.
Which is right depends on whether joining order and history matter, which is a question for the library, not a container detail.
Exercise: Pick containers for five access patterns
Choose a container for each, and say which operation drove the choice.
- Opening hours for each day of the week.
- Books looked up by ISBN thousands of times a day; nobody lists them by ISBN.
- Open loans, which must be printed in due-date order every morning, and are opened and closed all day.
- The last 20 pages a member has viewed, newest added at the end, the oldest dropped when there are more than 20.
- The tags on one book (typically 3 to 10), shown in alphabetical order, checked for duplicates when a tag is added.
Show the explained answer
std::array<OpeningHours, 7>. There are always exactly seven days, known when the code is written, and access is by index (day of the week). No allocation, and the size cannot drift.std::unordered_map<std::string, Book>(or ISBN to position or ID). The operation that matters is lookup by exact key, average O(1), and the keys never need an order.std::set<std::pair<Date, LoanId>>, sorted by due date and then ID. Opening and closing a loan are O(log n) insertions and removals, because a closing loan knows its own due date, and printing in due-date order is a walk through the set. (If loans had to be found by ID alone, add a second index from ID to due date, asMemberIndexdoes.) If loans were printed rarely, a vector sorted just before printing would also be reasonable.std::deque<PageId>. Pages are added at the back and dropped from the front, both O(1). A vector would need to erase its first element, moving the other 19, which for 20 elements is cheap too, so a vector is also defensible; the deque says “queue” more clearly.- A
std::vector<std::string>kept sorted, or astd::set<std::string>. With ten elements, either is fine; the vector is smaller and simpler, and a duplicate check bystd::binary_search(or even a plain search) costs nothing noticeable.std::setsaves writing the “keep sorted, refuse duplicates” code.
The point of the exercise is the reasoning: name the operation that happens most, choose the container that makes it cheap, and check that it does not make another frequent operation expensive.
Summary
Section titled “Summary”- Choose a container from how the data is used: by position, by key, in sorted order, at the ends, or with a fixed size.
std::vectoris the default;std::arrayfor fixed sizes;std::dequefor queues;std::unordered_mapfor fast lookup by key;std::mapandstd::setfor sorted data and range questions.- Big-O describes growth, not speed for small data; contiguous storage is often faster than its Big-O suggests.
- Adding to or removing from a container can invalidate references, pointers, and iterators into it. Do not keep them across changes; store keys or positions, and document how long any reference you hand out stays valid.