C++ STL Notes
Introduction
STL (Standard Template Library) is a powerful feature of C++ that provides ready-to-use classes and
functions for common data structures and algorithms.
Components of STL:
1. Containers
2. Algorithms
3. Iterators
4. Function Objects (Functors)
Containers
1. vector: Dynamic array.
Example:
vector<int> v = {1, 2, 3};
v.push_back(4); v.pop_back(); v[0];
2. list: Doubly linked list.
list<int> l; l.push_back(1); l.push_front(2);
3. deque: Double-ended queue.
deque<int> d; d.push_back(1); d.push_front(2);
4. set: Stores unique, sorted elements.
set<int> s; s.insert(1);
5. unordered_set: Stores unique elements, not sorted.
unordered_set<int> us;
C++ STL Notes
6. map: Key-value pairs, sorted by key.
map<string, int> m; m["apple"] = 2;
7. unordered_map: Key-value pairs, not sorted.
unordered_map<int, string> um;
Algorithms
Common algorithms from <algorithm> header:
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
max_element(v.begin(), v.end());
min_element(v.begin(), v.end());
count(v.begin(), v.end(), 3);
find(v.begin(), v.end(), 4);
binary_search(v.begin(), v.end(), 3);
lower_bound(v.begin(), v.end(), 3);
upper_bound(v.begin(), v.end(), 3);
Iterators
Used to traverse containers.
vector<int>::iterator it;
for(it = v.begin(); it != v.end(); ++it)
cout << *it;
Pair
C++ STL Notes
Used to store two heterogeneous objects together.
pair<int, string> p = make_pair(1, "one");
p.first, p.second;
Stack, Queue, Priority Queue
stack<int> s; s.push(1); s.pop();
queue<int> q; q.push(2); q.front();
priority_queue<int> pq; // Max-heap
priority_queue<int, vector<int>, greater<int>> minpq; // Min-heap
Tips
1. Start with vector, set, and map.
2. Use STL in coding practice for speed and reliability.
3. Refer to <algorithm>, <vector>, <map>, etc. headers.