C++ STL Containers: vector, map, and set by Example
A vector holds 3, 1, 2, grows to four elements, and reports size=4 front=3 back=4. A map holds two names and ages, gains a third, and reports size=3 bo=25. A set is given 5, 3, 5, 1, drops the duplicate, and reports size=3 contains 3: yes. The same guide shows why reading past the end of a vector is undefined behavior, why map bracket access inserts a missing key, and why iterating a map gives sorted order instead of insertion order.
Written November 11, 2026 · Tested with GCC 13.3.0 · 10 min read
- vector: an ordered list that grows
- map: lookup by name
- set: unique values in sorted order
- Which container for which job
What this guide is
A container holds a collection of values and decides how they are stored, found, and ordered. The C++ standard library ships dozens of them, and beginners reach for three first. A vector is an ordered list that grows. A map is a lookup table from a key to a value. A set is a collection of unique values kept in sorted order. The program uses GCC 13.3.0 with -std=c++17 -Wall -Wextra and exits with code 0.
The program
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <string>
int main() {
std::vector<int> v = {3, 1, 2};
v.push_back(4);
std::cout << "vector size=" << v.size() << " front=" << v.front() << " back=" << v.back() << "\n";
std::map<std::string, int> ages = {{"ana", 30}, {"bo", 25}};
ages["cy"] = 40;
std::cout << "map size=" << ages.size() << " bo=" << ages["bo"] << "\n";
std::set<int> s = {5, 3, 5, 1};
std::cout << "set size=" << s.size() << " contains 3: " << (s.count(3) ? "yes" : "no") << "\n";
return 0;
}
The exact output:
vector size=4 front=3 back=4
map size=3 bo=25
set size=3 contains 3: yes
Three details in the program deserve a second look before the sections below explain them. First, each container is created with a brace list, and each list says something about the container: the vector list is in the order the values stay in, the map list pairs each name with an age, and the set list contains a duplicate 5 that does not survive. Second, push_back and the bracket assignment are the two ways values enter a container in this program, and they behave differently: push_back appends, while ages["cy"] = 40 inserts a new key. Third, the program never asks for an element that is not there, and the sections below show what happens when code does, because each container answers that question differently.
vector: an ordered list that grows
A vector stores its elements in one contiguous block, in the order they were added. push_back appends a value at the end. In the program, v starts as {3, 1, 2}, v.push_back(4) makes it {3, 1, 2, 4}, and the output confirms it: size 4, front 3, back 4. size() counts the elements, front() returns the first, back() returns the last. A second run checked the last element by index and printed v[3]=4 size=4, which confirms that the fourth element sits at index 3, the last valid index.
Indexing starts at 0, so a vector of size 4 has valid indexes 0, 1, 2, and 3. Reading v[10] on a 4-element vector is not an error the compiler reports. The reference documentation states the rule plainly: operator[] performs no bounds checking, and if the index is not less than size(), the behavior is undefined. Undefined behavior means the program may print garbage, print the right answer by accident, or crash, and the outcome may change with the compiler, the flags, or the day. The guide states the rule and does not run the out-of-range read, because a program whose behavior is undefined proves nothing by running.
map: lookup by name
A map stores pairs of a key and a value, and finds a value by its key. In the program, ages starts with ana at 30 and bo at 25. The line ages["cy"] = 40 adds a third pair, and the output confirms the size is 3 and bo is still 25. Reading ages["bo"] returns the stored value. So far the bracket looks like an ordinary array access, and the surprise is what it does with a key that is not there.
A second program tested exactly that. It started with the same two names, then read ages["zoe"] for a name that was never added. The result printed zoe=0, and the size had grown from 2 to 3. The bracket did not report a missing key. It inserted one, with a value-initialized value, which is 0 for an int. The reference documentation states the same rule: the bracket operator inserts a value_type of the key and a default value if the key does not exist, and the inserted value is value-initialized. That is why the program above can use ages["cy"] = 40 to add a name: the bracket creates the pair, and the assignment sets its value.
The other two lookups do not insert. The same test program called find("nobody"), which returned the end iterator and printed not found, and the size stayed at 3. It then called at("nobody"), which threw std::out_of_range, and the size still stayed at 3. The rule is simple to state and easy to get backwards: brackets insert, find and at do not. Use brackets when adding a key on purpose, use find to test for a key without changing the map, and use at when a missing key should be an error instead of a silent new entry.
ages["zoe"] on a two-entry map returns 0 and grows the map to 3 entries, while find reports the key missing and at throws out_of_range, and neither changes the size. Bracket access is for insertion; find and at are for lookup.set: unique values in sorted order
A set holds one copy of each value, kept in sorted order. The reference documentation defines it in one sentence: a set is an associative container that contains a sorted set of unique objects, with sorting done using the key comparison function. In the program, s is created from {5, 3, 5, 1}. The duplicate 5 is dropped at construction, so the size is 3, and s.count(3) returns 1, which the program prints as contains 3: yes. count returns 1 when the value is present and 0 when it is not, because a set never holds a value twice.
A second run printed the set by iterating over it, and the output was 1 3 5. The values come out sorted, not in the order they were written in the brace list. That is the point of the container: the sorted order is maintained on every insertion, so iterating always visits the values smallest first. The same run confirmed that inserting into a set and reading it back needs no sorting step of its own, because the container keeps the order as an invariant rather than as a step the caller performs.
Which container for which job
The three containers overlap less than they first appear to, because each one is built around a different question. The table below states the question each one answers, and the program above demonstrates each row.
| Job | Container | Why |
|---|---|---|
| Keep values in the order they were added, and grow the list | vector |
Insertion order is preserved, push_back appends, and indexing is direct |
| Look a value up by a name or another key | map |
The key finds the value, and a missing key is either inserted by brackets or reported by find and at |
| Keep each value once, and visit them in sorted order | set |
Duplicates are dropped at insertion, and iteration is always sorted |
When the job is a list of scores in the order they were recorded, that is a vector. When the job is an age for each name, that is a map. When the job is the distinct words in a file, visited alphabetically, that is a set. When the job fits two rows, pick the row whose guarantee matters more: a vector that must stay unique needs a manual duplicate check on every insert, while a set that must remember insertion order needs a separate vector beside it, because the set sorts.
Trap: a map iterates in sorted order, not insertion order
ana, then bo, then zoe through the bracket, and printed the keys in iteration order: ana bo zoe. That happens to match the insertion order, so a second look is needed to see the trap, and the program above supplies it. The map in the main program is built from ana and bo, then cy is added. Iterating that map would print ana bo cy, which again matches insertion order only because the keys were added in alphabetical order already.Insert the same three names in a different order and the trap shows itself. A map built from cy, then ana, then bo still iterates as ana bo cy, because the iteration order is the key order, not the history of inserts. Code that prints a map and expects the output to follow the order the pairs were added will print a different order whenever the keys arrive out of alphabetical order, and the output will look wrong without any error to explain it. When insertion order matters, keep the keys in a vector in the order they arrived and use the map only for lookup, or pick a container whose order is insertion order.
Checklist
- Before choosing a container, name the question it must answer: order of arrival, lookup by key, or uniqueness in sorted order.
- Before reading
v[i], check thatiis less thanv.size(): bracket access on a vector performs no bounds checking, and an out-of-range read is undefined behavior. - Before reading
ages[key]for a key that may be missing, decide whether a missing key should insert a default value: if not, usefindto test oratto throw. - Before testing whether a value is in a set, use
count: it returns 1 when present and 0 when absent, because a set never holds a value twice. - Before iterating a set, expect sorted order: a set created from 5, 3, 5, 1 iterates as
1 3 5. - Before printing a map and expecting insertion order, check the key order: a map iterates sorted by key, so insert
cy,ana,boand it still printsana bo cy.
Related guides on this site
- C++ Variables and Data Types: Declaration, Initialization, and Sizes — the previous guide in this foundation series, where a variable is declared, brace initialization rejects narrowing, and an uninitialized variable earns a warning.
- C++ Pointers and References: Addresses, Dereferencing, and nullptr — the previous guide in this foundation series, where a pointer can be re-pointed and a reference cannot, and assigning to a reference writes through it.
- C++ Classes and Objects: Your First Class, Constructor, and Methods — the previous guide in this foundation series, where a Counter class prints hits=3 and a const method cannot change a member.
- C++20 Modules with CMake and Ninja — the first course guide, where modules replace headers.
- Modern C++ Guides: C++20 and C++23, Built and Run — the index of all the Modern C++ guides on this site.
Sources
- cppreference, std::vector — sequence container, contiguous storage,
push_back,size,front,back. - cppreference, vector operator[] — no bounds checking is performed, and if the index is not less than
size(), the behavior is undefined. - cppreference, std::map — sorted associative container, key to value lookup.
- cppreference, map operator[] — inserts a value-initialized value if the key does not exist;
findandatdo not insert. - cppreference, std::set — an associative container that contains a sorted set of unique objects, with sorting done using the key comparison function.
Keep Exploring
Seven tips and seven puzzles so far, each one a short runnable example with the fix explained.
Paste an AddressSanitizer, UBSan, or ThreadSanitizer report and get the bug, the file and line, and the fix \u2014 in plain language.
C++20 and C++23 features, migration paths, and measured trade-offs.
The full C++ hub \u2014 language basics, the standard library, coroutines, and measured comparisons.
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.