C++ STL速查

容器概览

容器访问插入用途
vectorO(1)O(1) amort.通用数组
dequeO(1)O(1) front/back队列/栈
listO(n)O(1)频繁插入删除
mapO(log n)O(log n)有序键值对
unordered_mapO(1) avgO(1) avg哈希表
setO(log n)O(log n)唯一有序值
priority_queueO(1) topO(log n)

算法

#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>()); // 降序 auto it = std::find(v.begin(), v.end(), 5); // 指向5的迭代器 auto pos = std::lower_bound(v.begin(), v.end(), 5); // 二分查找 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 << " "; });

智能指针

#include <memory> // unique_ptr — 独占所有权 auto p = std::make_unique<int>(42); auto q = std::move(p); // 转移所有权 // shared_ptr — 共享所有权(引用计数) auto sp = std::make_shared<std::vector<int>>(); sp->push_back(1); auto sp2 = sp; // 共享同一个向量 // weak_ptr — 非拥有引用 std::weak_ptr<int> wp = sp; if (auto locked = wp.lock()) { /* 仍然存活则使用 */ }