Modern C++ • C++20 baseline
STL Containers and Their Trade-Offs
Select a container using access patterns, ordering requirements, and invalidation rules.
std::vector is a strong default for sequential data because it is compact and cache-friendly. std::map maintains ordered keys, while std::unordered_map offers average constant-time lookup with hashing. Container choice affects complexity and iterator invalidation, so check the operations your code performs most often.
Key points
- Use vector unless the required operations justify another container.
- Do not retain iterators or references across operations that may invalidate them.
Example
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
const std::unordered_map<std::string, int> stock{
{"notebook", 8}, {"pen", 15}
};
if (const auto found = stock.find("pen"); found != stock.end()) {
std::cout << found->second << '\n';
}
}
What to expect
15
Practice exercise
Choose a container for a leaderboard that must stay sorted by score. Explain how duplicate scores should be represented.
Key idea: Choose containers based on semantics and measured access patterns, not habit.