C++ STL Reference
Container Overview
| Container | Access | Insert | Use Case |
|---|---|---|---|
| vector | O(1) | O(1) amort. | General array |
| deque | O(1) | O(1) front/back | Queue/stack |
| list | O(n) | O(1) | Frequent insert/delete |
| map | O(log n) | O(log n) | Sorted key-value |
| unordered_map | O(1) avg | O(1) avg | Hash map |
| set | O(log n) | O(log n) | Unique sorted values |
| priority_queue | O(1) top | O(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 */ }