C++ STL Reference

Container Overview

ContainerAccessInsertUse Case
vectorO(1)O(1) amort.General array
dequeO(1)O(1) front/backQueue/stack
listO(n)O(1)Frequent insert/delete
mapO(log n)O(log n)Sorted key-value
unordered_mapO(1) avgO(1) avgHash map
setO(log n)O(log n)Unique sorted values
priority_queueO(1) topO(log n)Heap

Algorithms

#include <algorithm> #include <numeric> #include <vector> std::vector<int> v = {5, 2, 8, 1, 9, 3}; std::sort(v.begin(), v.end()); // {1,2,3,5,8,9} std::sort(v.begin(), v.end(), std::greater<int>()); // descending auto it = std::find(v.begin(), v.end(), 5); // iterator to 5 auto pos = std::lower_bound(v.begin(), v.end(), 5); // binary search int sum = std::accumulate(v.begin(), v.end(), 0); // 28 std::transform(v.begin(), v.end(), v.begin(), [](int x){ return x*2; }); std::for_each(v.begin(), v.end(), [](int n){ std::cout << n << " "; });

Smart Pointers

#include <memory> // unique_ptr — exclusive ownership auto p = std::make_unique<int>(42); auto q = std::move(p); // transfer ownership // shared_ptr — shared ownership (ref counted) auto sp = std::make_shared<std::vector<int>>(); sp->push_back(1); auto sp2 = sp; // both point to same vector // weak_ptr — non-owning reference std::weak_ptr<int> wp = sp; if (auto locked = wp.lock()) { /* use if alive */ }