C++ STL
vector · map · set · queue · stack · unordered_map · iterator · algorithm
Sheet 2 of 3
C++17
Intermediate
Printable
STL Containers at a Glance
| Container | Header | Ordered? | Duplicates? | Access | Insert / Search | Use when… |
|---|---|---|---|---|---|---|
| vector | <vector> | Yes (index) | Yes | O(1) random | O(1) end / O(n) mid | Default sequence — fast random access |
| list | <list> | Yes (seq) | Yes | O(n) iter | O(1) anywhere | Frequent mid insertions/deletions |
| deque | <deque> | Yes (index) | Yes | O(1) random | O(1) front & back | Queue + random access |
| stack | <stack> | LIFO | Yes | top only | O(1) push/pop | LIFO — undo, DFS, backtracking |
| queue | <queue> | FIFO | Yes | front/back | O(1) push/pop | FIFO — BFS, task scheduling |
| priority_queue | <queue> | Heap | Yes | top only | O(log n) | Always access largest/smallest first |
| set | <set> | Sorted | No | iterator | O(log n) | Unique sorted elements |
| multiset | <set> | Sorted | Yes | iterator | O(log n) | Sorted with duplicates |
| map | <map> | By key | Keys: No | O(log n) | O(log n) | Key→value, sorted by key |
| unordered_map | <unordered_map> | No | Keys: No | O(1) avg | O(1) avg | Fast key→value lookup (hash map) |
| unordered_set | <unordered_set> | No | No | O(1) avg | O(1) avg | Fast membership test |
Default choice: Use vector unless you have a specific reason not to. It has the best cache performance and works with all STL algorithms.
vector
Create & Access
#include <vector> using namespace std; // Declare vector<int> v; vector<int> v2(5, 0); // {0,0,0,0,0} vector<int> v3 = {1,2,3,4}; // Access v3[0] // 1 — no bounds check v3.at(0) // 1 — throws if out of range v3.front() // 1 — first element v3.back() // 4 — last element v3.size() // 4 v3.empty() // false
Modify
v3.push_back(5); // add to end v3.pop_back(); // remove last v3.insert(v3.begin()+1, 99); // insert at idx 1 v3.erase(v3.begin()+2); // erase at idx 2 v3.clear(); // remove all v3.resize(10); // resize to 10 v3.reserve(100); // pre-allocate capacity v3.assign(5, 0); // replace with 5 zeros // 2D vector vector<vector<int>> mat(3, vector<int>(4,0)); mat[1][2] = 7;
Iterate
vector<int> v = {10,20,30}; // Range-for (C++11) — preferred for (int x : v) cout << x << " "; // Index loop for (size_t i = 0; i < v.size(); i++) cout << v[i]; // Iterator for (auto it = v.begin(); it != v.end(); ++it) cout << *it; // Modify in range-for for (int& x : v) x *= 2; // double each
map & unordered_map
map — sorted by key O(log n)
#include <map> map<string, int> scores; // Insert scores["Alice"] = 92; scores.insert({"Bob", 85}); scores.emplace("Carol", 78); // Access scores["Alice"] // 92 (creates if missing!) scores.at("Alice") // 92 (throws if missing) // Check existence scores.count("Bob") // 1 or 0 scores.find("Bob") != scores.end() // Erase scores.erase("Bob"); // Iterate (sorted by key) for (auto& [k, v] : scores) cout << k << ": " << v << "\n";
unordered_map — hash O(1) avg
#include <unordered_map> unordered_map<string, int> freq; // Count word frequency vector<string> words = {"a","b","a"}; for (auto& w : words) freq[w]++; // freq["a"]=2, freq["b"]=1 // get_or_default pattern int val = freq.count("x") ? freq["x"] : 0; // C++17 — contains() if (freq.contains("a")) cout << "found\n";
map[ ] creates keys! Accessing a missing key with map["key"] inserts it with a default value. Use .count() or .find() to check existence safely.
set & unordered_set
set — sorted unique elements
#include <set> set<int> s = {3,1,4,1,5}; // stores: {1, 3, 4, 5} — sorted, unique s.insert(2); s.erase(3); s.count(4) // 1 (exists) or 0 s.size() // Iteration — always sorted for (int x : s) cout << x << " "; // 1 2 4 5 // Lower/upper bound auto it = s.lower_bound(3); // first >= 3 auto it = s.upper_bound(3); // first > 3
unordered_set — hash O(1) avg
#include <unordered_set> unordered_set<string> visited; visited.insert("home"); visited.insert("work"); // O(1) membership check if (visited.count("home")) cout << "already visited\n"; // Remove duplicates from vector vector<int> v = {1,2,2,3}; unordered_set<int> unique(v.begin(), v.end());
stack · queue · priority_queue
stack — LIFO
#include <stack> stack<int> st; st.push(1); st.push(2); st.push(3); st.top() // 3 — peek st.pop(); // remove 3 st.top() // 2 now st.size() // 2 st.empty() // false // Pop until empty while (!st.empty()) { cout << st.top(); st.pop(); }
queue — FIFO
#include <queue> queue<string> q; q.push("first"); q.push("second"); q.push("third"); q.front() // "first" — peek front q.back() // "third" — peek back q.pop(); // remove "first" q.front() // "second" now q.size() // 2 // BFS pattern while (!q.empty()) { auto curr = q.front(); q.pop(); /* process curr */ }
priority_queue — max-heap
#include <queue> // Max-heap (default) priority_queue<int> pq; pq.push(3); pq.push(1); pq.push(4); pq.top() // 4 — always max pq.pop(); // removes 4 // Min-heap priority_queue<int, vector<int>, greater<int>> minpq; minpq.push(3); minpq.push(1); minpq.top() // 1 — always min
stack/queue have no iterators — you can't loop over them directly. If you need to inspect elements, use deque or vector instead and use it like a stack/queue manually.
Iterators
Iterator Types & Operations
vector<int> v = {10,20,30,40}; auto it = v.begin(); // points to 10 auto end = v.end(); // one past last *it // 10 — dereference ++it // advance to 20 it += 2 // jump 2 (random access) *it // 40 // Reverse iterator for (auto it = v.rbegin(); it != v.rend(); ++it) cout << *it; // 40 30 20 10 // advance / distance #include <iterator> advance(it, 2); distance(v.begin(), it);
Insert & Erase with Iterators
vector<int> v = {1,2,3,4,5}; // Insert before position 2 v.insert(v.begin()+2, 99); // {1,2,99,3,4,5} // Erase element at index 3 v.erase(v.begin()+3); // Erase a range [1, 3) v.erase(v.begin()+1, v.begin()+3);
<algorithm> — STL Algorithms
Sort & Search
#include <algorithm> vector<int> v = {3,1,4,1,5}; // Sort ascending sort(v.begin(), v.end()); // Sort descending sort(v.begin(), v.end(), greater<int>()); // Custom comparator (lambda) sort(v.begin(), v.end(), [](int a, int b) { return a % 2 < b % 2; }); // Find — returns iterator auto it = find(v.begin(), v.end(), 4); if (it != v.end()) cout << "found: " << *it; // Binary search (sorted only!) binary_search(v.begin(), v.end(), 4); // bool
Count, Min, Max
count(v.begin(), v.end(), 1) // how many times 1 appears count_if(v.begin(), v.end(), [](int x) { return x%2==0; }); min_element(v.begin(), v.end()); max_element(v.begin(), v.end()); // min / max of two values min(3, 7) // 3 max(3, 7) // 7
Transform & Fill
#include <algorithm> vector<int> v = {1,2,3,4}; vector<int> out(v.size()); // Square every element transform(v.begin(), v.end(), out.begin(), [](int x) { return x*x; }); // out = {1,4,9,16} // Fill a range with a value fill(v.begin(), v.end(), 0); // Reverse in-place reverse(v.begin(), v.end()); // Unique — removes consecutive dups // (sort first for all dups) sort(v.begin(), v.end()); auto last = unique(v.begin(), v.end()); v.erase(last, v.end());
any_of · all_of · none_of
vector<int> v = {2,4,6,8}; all_of(v.begin(), v.end(), [](int x) { return x%2==0; }); // true — all even any_of(v.begin(), v.end(), [](int x) { return x > 5; }); // true — 6 and 8 qualify none_of(v.begin(), v.end(), [](int x) { return x < 0; }); // true — no negatives
numeric — accumulate & iota
#include <numeric> vector<int> v = {1,2,3,4,5}; // Sum all elements int sum = accumulate( v.begin(), v.end(), 0); // sum = 15 // Product int prod = accumulate( v.begin(), v.end(), 1, [](int a, int b) { return a*b; }); // prod = 120 // Fill with 0,1,2,3... vector<int> seq(5); iota(seq.begin(), seq.end(), 0); // {0,1,2,3,4}
Partition & Remove-if
vector<int> v={1,2,3,4,5,6}; // Erase-remove idiom v.erase( remove_if(v.begin(), v.end(), [](int x){return x%2==0;}), v.end()); // v = {1,3,5} — odds only // Partition — evens first partition(v.begin(), v.end(), [](int x){return x%2==0;});
std::string
Create & Common Operations
#include <string> string s = "Hello"; string s2 = s + " World"; // concat s.size() // 5 s.length() // same s.empty() // false s[0] // 'H' s.at(1) // 'e' s.front() // 'H' s.back() // 'o' s.substr(1, 3) // "ell" s.find("ll") // 2 (index) s.find("xyz") // string::npos s.replace(1,3,"ELL") // "HELLO" s.erase(1, 2) // erase 2 chars at 1
Conversion & Streams
// int / double ↔ string string ns = to_string(42); int n = stoi("42"); double d = stod("3.14"); long l = stol("100"); // C string ↔ std::string const char* cs = s.c_str(); string s2(cs); // String stream — split / parse #include <sstream> stringstream ss("10 20 30"); int a, b, c; ss >> a >> b >> c; // a=10, b=20, c=30
Lambdas & auto (C++11+)
Lambda Syntax
// [capture](params) -> ret { body } // Basic lambda auto add = [](int a, int b) { return a + b; }; add(3, 4) // 7 // Capture by value [=] int limit = 5; auto small = [=](int x) { return x < limit; }; // Capture by reference [&] int total = 0; auto acc = [&](int x) { total += x; // modifies outer total }; // Use with algorithm vector<int> v={1,2,3,4,5}; for_each(v.begin(), v.end(), acc); // total = 15
auto & Modern C++ Shortcuts
// auto — let compiler infer type auto x = 42; // int auto d = 3.14; // double auto s = string("hi"); // Structured bindings (C++17) map<string,int> m; for (auto& [key, val] : m) cout << key << val; // pair and tuple pair<int,string> p = {1,"hi"}; p.first; p.second; tuple<int,string,double> t{1,"a",3.0}; get<0>(t); // 1 auto& [a,b,c] = t; // unpack
C++ STL Mastery Checklist
| vector & Strings | Key point |
|---|---|
| Add to end | v.push_back(x) |
| Remove from end | v.pop_back() |
| Safe access | v.at(i) |
| Pre-allocate | v.reserve(n) |
| Substring | s.substr(pos, len) |
| String to int | stoi("42") |
| map · set · queue | Key point |
|---|---|
| Safe map access | m.at("key") |
| Check key exists | m.count("k") |
| Fast lookup | unordered_map |
| Unique sorted | set<T> |
| Max always on top | priority_queue |
| Min-heap | greater<T> comparator |
| Algorithms | Key point |
|---|---|
| Sort ascending | sort(b, e) |
| Sort descending | sort(b,e,greater<>()) |
| Find element | find(b, e, val) |
| Apply function | transform(b,e,out,fn) |
| Sum elements | accumulate(b,e,0) |
| Remove+erase | erase(remove_if(...)) |
Next up → Sheet 3: Cpp OOP ·
classes · templates · RAII · smart pointers · inheritance · polymorphism · virtual · move semantics