01 / 20

Choosing
Container Types

Learn how to pick the right C++ container for the job by understanding access patterns, performance trade-offs, and real-world scenarios.

C++

What Is a Container?

A container is an object that stores a collection of other objects (its elements). The C++ Standard Library provides many container types, each with different strengths. Choosing the right one directly affects your program's performance and clarity.

The Big Three Categories

Sequence
Elements stored in a linear order you control: vector, deque, list, array
Associative
Elements sorted by key for fast lookup: set, map, multiset, multimap
Unordered
Hash-table based for average \( O(1) \) lookup: unordered_set, unordered_map

Why the Choice Matters

Different containers have vastly different performance for the same operation. Choosing poorly can turn an \( O(1) \) lookup into an \( O(n) \) scan, or make insertions hundreds of times slower.

Number of elements (n) Time O(1) O(log n) O(n) 0 large

The Core Decision Rule

Need key-value pairs? Yes Need sorted order? Yes std::map No std::unordered_map No Need random access by index? Yes std::vector No Frequent insert/remove in middle? Yes std::list No std::deque

Sequence Containers Deep Dive

vector
Contiguous memory. \( O(1) \) random access. \( O(1) \) amortized push_back. Best cache performance.
deque
Double-ended. \( O(1) \) push/pop at both front and back. \( O(1) \) random access but slightly slower than vector.
list
Doubly-linked. \( O(1) \) insert/erase anywhere (given iterator). No random access. Poor cache locality.

Associative vs Unordered

Associative (map/set) Unordered (unordered_map/set)
Structure Balanced BST (red-black tree) Hash table
Lookup \( O(\log n) \) \( O(1) \) average
Insert \( O(\log n) \) \( O(1) \) average
Ordered iteration Yes (sorted) No
Worst case \( O(\log n) \) guaranteed \( O(n) \) on hash collision

How to Choose: Step by Step

1
Identify the access pattern. Do you access by index, by key, or only at the ends?
2
Determine the hottest operation. Is it insert, erase, lookup, or iteration?
3
Check ordering needs. Do you need elements sorted, or is insertion order sufficient?
4
Consider uniqueness. Should duplicates be allowed? (multi-variants or vector).
5
Default to vector. If nothing special is needed, std::vector is almost always the right choice.

Example 1: Game Leaderboard

Scenario: You are building a game leaderboard. You need to store player names with their scores, display the top 10 at any time, and quickly update a player's score.

// Score as key (sorted), name as value std::map<int, std::string, std::greater<int>> leaderboard; leaderboard[9500] = "Alice"; leaderboard[8700] = "Bob"; // Top 10: iterate first 10 entries

Example 2: Spell Checker

Scenario: A spell checker must quickly determine whether a word exists in a 100,000-word dictionary. Order does not matter: you just need "is this word valid?"

std::unordered_set<std::string> dictionary; dictionary.insert("algorithm"); dictionary.insert("binary"); if (dictionary.count("helo") == 0) std::cout << "Misspelled!";

Example 3: Undo History

Scenario: A text editor needs an undo feature. The most recent action is undone first (LIFO). You only ever access the top element.

std::stack<std::string> undoStack; undoStack.push("Type 'Hello'"); undoStack.push("Delete word"); // Undo last action std::string lastAction = undoStack.top(); undoStack.pop();

Memory Layout Matters

std::vector (contiguous memory) A B C D E Cache-friendly ✓ std::list (scattered nodes + pointers) A B C D Cache-unfriendly ✕

Big-O at a Glance

Operation vector deque list unordered_map
Access [i] \( O(1) \) \( O(1) \) \( O(n) \) N/A
Push back \( O(1)^* \) \( O(1) \) \( O(1) \) N/A
Push front \( O(n) \) \( O(1) \) \( O(1) \) N/A
Insert mid \( O(n) \) \( O(n) \) \( O(1) \) N/A
Find by key \( O(n) \) \( O(n) \) \( O(n) \) \( O(1) \)

When vector Wins

Even for operations where list has a better theoretical Big-O (like mid-insertion), vector often wins in practice for small to medium sizes due to cache locality and low overhead.

✓ Use vector when:
You mostly iterate, append, or access by index. You do not know the container type to pick. Size is under ~100,000 elements.
✕ Avoid vector when:
You frequently insert/erase in the middle of millions of elements, or you need fast front insertion (use deque instead).

Common Mistakes

✕ Using list "because insertions are O(1)"
Only true if you already have an iterator to the position. Finding that position is still \( O(n) \). Cache misses make list slower than vector for small data.
✕ Using map when order is not needed
Paying \( O(\log n) \) per lookup when unordered_map gives \( O(1) \). Only use map if you need sorted iteration.
✕ Ignoring iterator invalidation
Inserting into a vector may invalidate all iterators. Using an invalidated iterator is undefined behavior: a silent, dangerous bug.

Question 1 of 5

You need to store 10,000 student IDs and look each one up by ID number as fast as possible. Order does not matter. Which container is best?

Question 2 of 5

A music playlist needs to display songs in alphabetical order and allow adding new songs efficiently. Which container fits best?

Question 3 of 5

What is the average time complexity of looking up a key in an std::unordered_map?

Question 4 of 5

You are processing a stream of data and need to remove elements from the front and add elements to the back as fast as possible. Which container is ideal?

Question 5 of 5

Why is std::vector often faster than std::list in practice, even for operations where list has a better Big-O?