Competitive Programming & Systems
C++ STL (Standard Template Library) Cheat Sheet
Quick syntax reference for vectors, maps, heaps, and algorithms in C++20. Run and inspect snippets directly in the ZenCompiler GCC 13 sandbox.
std::vector (Dynamic Array)
Dynamic array with contiguous storage, amortized O(1) push_back.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {4, 1, 8, 3, 2};
v.push_back(10);
// Sort in ascending order
std::sort(v.begin(), v.end());
for (int x : v) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}std::map & std::unordered_map
Associative key-value containers. map (Red-Black Tree O(log N)), unordered_map (Hash Table O(1)).
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<std::string, int> freq;
std::string words[] = {"apple", "banana", "apple", "cherry", "banana", "apple"};
for (const auto& w : words) {
freq[w]++;
}
for (const auto& [word, count] : freq) {
std::cout << word << ": " << count << std::endl;
}
return 0;
}std::priority_queue (Max & Min Heap)
Heap data structure for O(log N) push and O(1) top access.
#include <iostream>
#include <queue>
#include <vector>
int main() {
// Default: Max-heap
std::priority_queue<int> max_heap;
max_heap.push(10);
max_heap.push(30);
max_heap.push(20);
std::cout << "Max element: " << max_heap.top() << std::endl; // 30
// Min-heap: greater<int>
std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap;
min_heap.push(10);
min_heap.push(30);
min_heap.push(20);
std::cout << "Min element: " << min_heap.top() << std::endl; // 10
return 0;
}