What is the STL?
The Standard Template Library (STL) provides generic, reusable containers and algorithms. The main components are containers, iterators, and algorithms.
vector — Dynamic Array
#include <vector>
using namespace std;
vector<int> v = {3, 1, 4, 1, 5};
v.push_back(9); // add to end
v.pop_back(); // remove from end
cout << v[0]; // 3
cout << v.size(); // 5
for (auto x : v) cout << x << " "; // 3 1 4 1 5
map — Key-Value Store
#include <map>
map<string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;
cout << scores["Alice"]; // 95
scores.erase("Bob");
for (auto& [key, val] : scores) { // C++17 structured binding
cout << key << ": " << val << "
";
}
set — Unique Sorted Elements
#include <set>
set<int> s = {5, 2, 8, 2, 1};
// s contains: {1, 2, 5, 8} — sorted, no duplicates
s.insert(3);
s.erase(2);
cout << s.count(5); // 1 (exists), 0 (not exists)
queue and stack
#include <queue>
#include <stack>
queue<int> q;
q.push(1); q.push(2); q.push(3);
cout << q.front(); // 1
q.pop();
stack<int> st;
st.push(10); st.push(20);
cout << st.top(); // 20
st.pop();
Sorting and Algorithms
#include <algorithm>
vector<int> v = {5, 2, 8, 1, 9};
sort(v.begin(), v.end()); // ascending
sort(v.begin(), v.end(), greater<int>()); // descending
auto it = find(v.begin(), v.end(), 8); // find element
int cnt = count(v.begin(), v.end(), 1); // count occurrences
int mx = *max_element(v.begin(), v.end()); // maximum
unordered_map — O(1) Hash Map
#include <unordered_map>
unordered_map<string, int> freq;
string word;
while (cin >> word) freq[word]++;
// O(1) average lookup vs O(log n) for map