CPP-STL-Notes โ interactive website
Master the C++ Standard Template Library
One-stop, beginner-friendly notes on the C++ STL โ rebuilt from the GitHub repo + all 7 STL Docs Word docs, 2 PDFs, and every linked Google Drive resource (main notes, Top-50 Algorithms, DS-Build-From-Scratch). With copy-paste code, method tables, complexity charts and official references.
STL Docs โ Basic STL Usage.docx
๐ฆ Containers & Vectors <vector> <algorithm> <limits>
A container holds a collection of same-type elements with add / remove / access ops. STL gives you vector, array, list, map, setโฆ โ each tuned for different needs.
A vector is a dynamic array that resizes itself. Benefits over raw arrays: grows/shrinks dynamically, bounds-checked access via at(), easily copied/resized.
#include <vector> | Key methods: push_back, pop_back, size, front, backDeclaration โ 1D & 2D
// 1-D
vector<int> v;
vector<int> v2(size, val); // size cells filled with val
vector<int> v3{1,2,3,4,5};
vector<string> fruits{"Apple","Banana","Orange"};
// 2-D
vector<vector<int>> m;
vector<vector<int>> m2{{1,2,3},{4,5,6},{7,8,9}};
vector<vector<int>> mat(m, vector<int>(n, val)); // m rows x n cols
Traversing
// index loop
for (int i = 0; i < (int)v.size(); i++) cout << v[i] << " ";
// range loop
for (auto x : v) cout << x << " ";
// iterator
for (auto it = v.begin(); it != v.end(); ++it) cout << *it << " ";
end() points past the last element โ it does not point to a valid element. Always compare with != end().Method reference
size() / max_size() / capacity()elements count / max possible / currently allocated slots. For 2D: m.size()=rows, m[0].size()=cols.push_back(x) / pop_back()add/remove from back in amortised O(1).front() / back()first / last element.begin() / end()iterators to first / past-last element.find(b,e,val)it = find(v.begin(), v.end(), 4); โ iterator to first match or v.end(). Check it == v.end() for โnot foundโ. *it = value, it - v.begin() = index. You can subtract iterators: it2 - it1 = distance.sort(b,e,comp?)sort(v.begin(), v.end()) ascending; sort(v.begin(), v.end(), greater<int>()) descending. Strings sort by ASCII: "bC78ip" โ "78Cbip".insert(pos,val) / erase(pos) / reverse / clear / resizev.insert(v.begin()+i, val); v.erase(v.begin()+2) (takes iterator, avoid on huge vectors); reverse(s.begin(), s.end()); clear() empties but keeps capacity; resize(n) fills new slots with 0.count / min,max_element / numeric_limitscount(v.begin(),v.end(),2) (<algorithm>, chars/digits only โ not substrings); *max_element(a.begin(),a.end()); numeric_limits<int>::max() from <limits> โ portable INT_MAX.Custom comparator (sort)
bool desc(int a, int b){ return a > b; } // true โ a before b
sort(nums.begin(), nums.end(), desc);
// sort pairs by first, then second
bool cmp(const pair<int,int>& a, const pair<int,int>& b){
if (a.first != b.first) return a.first < b.first;
return a.second < b.second;
}
vector<pair<int,int>> p{{5,2},{2,9},{1,9},{5,1}};
sort(p.begin(), p.end(), cmp);
true โ first arg comes before second. Return false โ opposite order.resize() โ 1D & 2D pattern from notes
vector<int> v1; v1.resize(5); // {0,0,0,0,0}
vector<vector<int>> v2; v2.resize(5, vector<int>(5)); // 5x5 zeros
source STL Docs / Basic STL Usage.docx + Basic STL Usage-Gen-3.pdf
STL Docs โ Numbers, Arrays, String STL Usage.docx
๐ค Strings, Arrays & Numbers <string> <utility> <sstream> <cctype>
Case transform & swap
transform(s.begin(), s.end(), s.begin(), ::toupper); // lower โ UPPER
transform(s.begin(), s.end(), s.begin(), ::tolower); // UPPER โ lower
toupper('a'); tolower('Z'); // single char
swap(s1[x], s1[y]); // <utility> โ works for int arrays too
string โ int
string s = "123"; int n = stoi(s); // <string>; throws invalid_argument if bad
string t = to_string(456); // int โ string
try { stoi("abc"); } catch (const invalid_argument& e){ cout << e.what(); }
Reverse / compare / substr
reverse(s1.begin(), s1.end()); // "Hello" โ "olleH"
s1.compare(s2); // 0 โ equal | (s1 == s2) works too
if (str1 <= str2) { /* dictionary order; UPPER < lower */ }
string a = str.substr(pos, len); // substr(pos,len)
string first = str.substr(0, str.size()/2);
string second = str.substr(str.size()/2);
string s = "" + 'a'; // ERROR and "" + s.back() fail (char โ string). Do: string x=""; x = x + s.back(); or use append().Parsing with istringstream
#include <sstream>
string input = "42 3.14 hello world";
istringstream iss(input);
int n; double d; string w1,w2;
iss >> n >> d >> w1 >> w2; // 42, 3.14, hello, world
// reuse:
iss.clear(); iss.str("");
Char / type helpers
isalnum(c) / isdigit(c)<cctype>. Non-zero โ true. Only pass a char, not a string: isdigit(str[1]).typeid(x).name()<typeinfo> โ debug helper: typeid('a').name() // c.abs / fabs / min / max / INT_MIN / INT_MAXabs(int) (<cstdlib>), fabs(double) (<cmath>). โ ๏ธ abs(s1.length()-s2.length()) errors (size_t!) โ hoist to int first. min(a,b)/max(a,b); INT_MIN/INT_MAX from <climits>.charโint digit trickint d = ch - '0'; // '5'โ5 (implicit cast). (int)ch gives ASCII 53 โ wrong!STL Docs โ Stack, Queue and Linked Lists.docx
๐ฅ Stack, Queue & Linked Lists <stack> <queue> <list> <forward_list>
Stack โ LIFO
stack<int> st;
st.push(5); st.push('A');
st.pop(); // no return!
int t = st.top(); // peek
st.empty(); st.size(); // cast: (int)st.size()
Queue โ FIFO
queue<int> q;
q.push(1); q.push(2);
q.pop();
q.front(); q.back();
q.empty(); q.size();
std::list โ doubly linked
#include <list>
list<int> L;
L.push_back(10); L.push_front(5);
L.pop_back(); L.pop_front();
L.insert(it, val); L.erase(it);
L.size(); L.empty();
for (auto it=L.begin(); it!=L.end(); ++it) cout << *it << " ";
std::forward_list โ singly linked (lighter)
#include <forward_list>
forward_list<int> F{30,20,10}; // push_front only!
F.push_front(5); F.pop_front();
F.insert_after(it, 25); F.erase_after(it);
F.remove(20); F.unique(); F.sort();
// insert at end via before_begin():
auto it = F.before_begin(); // then insert_after
list = 2 pointers/node + bidirectional; forward_list = 1 pointer/node, forward-only, no push_back() โ but faster & leaner.STL Docs โ Hash Map and Hash Table.docx
๐บ๏ธ Hash Map & Hash Table <unordered_map> <map>
โHash Map performs insert / delete / traversal in constant time.โ It maps unique key โ value.
| unordered_map (Hash Map) | map (Balanced BST / Red-Black) |
|---|---|
| Hash table, unsorted, avg O(1) insert/delete/find | Sorted by key, O(log n) insert/delete/find, lexicographic order |
unordered_map<string,int> table;
table["C++"] = 1; // easiest insert
table.insert(make_pair("C++",1));
table.insert({"C++",1});
unordered_map<int, vector<int>> hm;
hm[0].push_back(1); hm[0].push_back(2); hm[1].push_back(3);
table["C++"]; table.at("C++"); // fetch
table.find(key) == table.end(); // existence?
table.count("C++"); table.size(); table.erase("C++");
unordered_map<string,int>::iterator it;
for (it = table.begin(); it != table.end(); ++it)
cout << it->first << ": " << it->second << "\n"; // first=key second=value
'\0'/0 (int/char) or "" (string) โ so if (mp[k]=='\0') detects โnever setโ (avoid comparing directly to 0 to dodge real-zero confusion).unordered_set snippet in Sets.STL Docs โ Heap and Priority Queue.docx
โฐ๏ธ Heap & Priority Queue <queue> <vector> <functional>
A priority_queue is a container adapter over a heap โ O(1) peek at min/max, O(log n) push/pop. Default = max-heap.
priority_queue<int> pq; // max-heap
pq.push(10); pq.push(20); pq.push(30);
while(!pq.empty()){ cout << pq.top() << " "; pq.pop(); } // 30 20 10
priority_queue<int, vector<int>, greater<int>> mn; // min-heap
priority_queue<pair<int, vector<pair<int,int>>>> cont; // nested example from notes
Max-heap
Parent โฅ children, root = max. Array layout: children of i at 2i+1, 2i+2. Insert/delete O(log n), peek O(1). priority_queue<int> pq builds one by default.
Min-heap
Parent โค children, root = min โ ideal for Dijkstra. Duplicates are kept (pop extras as needed).
// custom comparator โ min-heap
struct Cmp {
bool operator()(const int& a, const int& b){ return a > b; }
};
priority_queue<int, vector<int>, Cmp> pq2;
// 2nd template param = underlying container (default vector), 3rd = comparator (default less โ max-heap)
operator() overloading = โfunction-call operatorโ โ the queue calls it to order elements.STL Docs โ Sets Containers in C++.docx
๐ Sets <set> <unordered_set>
set = unique + sorted (Red-Black tree, O(log n)). unordered_set = unique + hashed, unordered (avg O(1), worst O(n) on collisions).
#include <set>
set<int> s{1,2,3,4};
s.insert(10); s.erase(20);
if (s.find(20) != s.end()) cout << "found";
for (auto it=s.begin(); it!=s.end(); ++it) cout << *it << " ";
// NOTE: no s[i] โ use iterators. s.end()==s.find(v) โ absent. 1-arg find (vs 3-arg vector find).
#include <unordered_set>
unordered_set<string> u{"apple","banana","orange"};
u.insert("pear"); u.erase("banana");
Remove duplicates, keep order (from notes)
vector<int> dedup(vector<int>& nums){
unordered_set<int> seen; vector<int> res;
for (int x : nums) if (seen.insert(x).second) res.push_back(x);
return res; // insert() โ pair<it,bool>; .second==true โ was new
}
load_factor (default 1.0) = elems/bucket; great for fast lookup / union / intersection; not for ordered iteration.STL Docs โ Bit Manipulation, Math & Geometry.docx
๐งฎ Bit Manipulation, Math & Geometry
num << 1; // ร2 (5 << 1 โ 10) โ faster than *2 in contests
num >> 1; // รท2 (5 >> 1 โ 2, fraction dropped)
1 << n; // 2^n
__builtin_popcount(5); // โ 2 (count of 1-bits)
(num & 1); // LSB check: 5&1==1. 5=0101, 1=0001. Great for masking.
| Type | Alias | Size |
|---|---|---|
uint8_t | unsigned char | 1 byte |
uint16_t | unsigned short | 2 bytes |
uint32_t | unsigned int | 4 bytes |
uint64_t | unsigned long long | 8 bytes |
Repo PDFs โ Algorithm Time Complexity.pdf
โฑ๏ธ Complexity Cheatsheet
The repoโs Algorithm Time Complexity.pdf is scanned images, so hereโs the standard STL summary it covers โ verified against cppreference.
| Container | Access | Insert / Push | Erase / Pop | Find |
|---|---|---|---|---|
vector | O(1) | amort. O(1) back | O(n) mid / O(1) back | O(n) |
string | O(1) | O(1) back | O(n) | O(nยทm) substr search |
list / forward_list | O(n) | O(1) w/ iterator | O(1) w/ iterator | O(n) |
stack / queue | O(1) top/front | O(1) | O(1) | โ |
map / set | O(log n) | O(log n) | O(log n) | O(log n) |
unordered_map / unordered_set | avg O(1) | avg O(1) | avg O(1) | avg O(1) |
priority_queue | O(1) top | O(log n) | O(log n) | โ |
| Algorithm (<algorithm>) | Avg | Note |
|---|---|---|
sort | O(n log n) | introsort; custom comparator allowed |
find / count | O(n) | linear scan; count wonโt find substrings |
reverse | O(n) | in-place |
min/max_element | O(n) | returns iterator |
binary_search (sorted) | O(log n) | requires sorted range |
Followed link โ Top 50 Algorithms Drive folder
๐ Top 50 Algorithms Google Drive
Followed from readme.md โ Extra Resources โ Top 50 Algorithms. The folder organises must-know patterns + a review sheet:
Binary search, two pointers, merge/quick/heap sort, counting sort.
Sliding window, KMP, Rabin-Karp, anagrams, palindromes.
DFS/BFS, Dijkstra, Union-Find, MST, topo-sort, LCA.
Knapsack, LIS, LCS, coin change, grid paths.
Intervals, Huffman, GCD/LCM, sieve, modular arithmetic, geometry.
N-Queens, subsets, permutations, + Algorithm Review Sheet & Top 50 Must-Know docs.
Followed link โ Data Structures, Build from Scratch Drive folder
๐๏ธ Data Structures โ Build From Scratch
Followed from readme.md โ Extra Resources โ Data Structures, Build from Scratch. Implement each yourself once โ then use the STL version with confidence:
Dynamic array: capacity doubling, amortised push.
Array- and linked-backed LIFO/FIFO + circular buffer.
Singly/doubly, reversal, cycle detection.
Hashing, chaining vs open addressing, load factor.
BST, traversals, AVL/Red-Black intuition.
Adj. list/matrix, BFS/DFS, shortest paths.
Main live-notes folder (with Basics and Essentials of C++ + Misc extras not in the repo): drive.google.com/โฆ/STL-notes
Every link in the repo, followed
๐ All Resources Hub
mohitdhami/CPP-STL-Notes โ readme, issues, contributions.
Basic STL, Basics & Essentials of C++, Bit/Math, HashMap, Heap, Misc, Strings, Sets, Stack/Queue/Lists.
Backtracking, DP, Graphs, Greedy, Math, Searching, Sorting, String, Tree + review sheet.
Vector, Stack, Queue, Linked List, Hash Table, Tree, Graph.
Direct from GitHub (also mirrored in this siteโs sidebar).
Always cross-check with the standard docs.