STL教程
C++ STL详解
这次稍微搞得少点,肝爆了
观众:21513字符,搞笑呢???
一、STL概述
STL(Standard Template Library)是C++标准库的核心组件,提供了通用的数据结构和算法。STL主要包含以下六大组件:
- 容器(Containers):存储数据的对象
- 迭代器(Iterators):用于遍历容器元素的对象
- 算法(Algorithms):操作容器元素的函数
- 函数对象(Functors):具有函数行为的对象
- 适配器(Adapters):修改其他组件接口的组件
- 分配器(Allocators):处理内存分配的组件
二、容器(Containers)
2.1 序列容器
vector
#include <vector>
#include <iostream>
int main() {
std::vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
std::vector<int> v2(5, 100);
std::vector<int> v3(v.begin(), v.end());
std::cout << v[0] << " " << v.at(1) << std::endl;
std::cout << "Size: " << v.size() << std::endl;
std::cout << "Capacity: " << v.capacity() << std::endl;
v.pop_back();
v.insert(v.begin() + 1, 15);
v.erase(v.begin());
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
v.clear();
std::cout << "Empty: " << (v.empty() ? "Yes" : "No") << std::endl;
return 0;
}
list
#include <list>
#include <iostream>
int main() {
std::list<int> lst;
lst.push_back(10);
lst.push_front(5);
lst.push_back(20);
std::list<int> lst2(3, 50);
std::list<int> lst3(lst.begin(), lst.end());
std::cout << lst.front() << " " << lst.back() << std::endl;
lst.pop_front();
lst.pop_back();
lst.insert(++lst.begin(), 15);
lst.remove(15);
lst.sort();
lst.reverse();
for (auto i : lst) {
std::cout << i << " ";
}
std::cout << std::endl;
lst.clear();
return 0;
}
deque
#include <deque>
#include <iostream>
int main() {
std::deque<int> dq;
dq.push_back(10);
dq.push_front(5);
dq.push_back(20);
std::deque<int> dq2(4, 25);
std::deque<int> dq3(dq.begin(), dq.end());
std::cout << dq[0] << " " << dq.at(1) << std::endl;
std::cout << dq.front() << " " << dq.back() << std::endl;
dq.pop_front();
dq.pop_back();
dq.insert(dq.begin() + 1, 15);
dq.erase(dq.begin());
for (auto i : dq) {
std::cout << i << " ";
}
std::cout << std::endl;
dq.clear();
return 0;
}
array
#include <array>
#include <iostream>
int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
std::array<int, 5> arr2 = {10, 20, 30, 40, 50};
std::cout << arr[0] << " " << arr.at(1) << std::endl;
std::cout << arr.front() << " " << arr.back() << std::endl;
std::cout << "Size: " << arr.size() << std::endl;
arr.fill(100);
arr.swap(arr2);
for (auto i : arr) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
forward_list
#include <forward_list>
#include <iostream>
int main() {
std::forward_list<int> flist;
flist.push_front(10);
flist.push_front(5);
flist.push_front(1);
flist.insert_after(flist.begin(), 7);
flist.erase_after(flist.begin());
flist.sort();
flist.reverse();
flist.remove(5);
for (auto i : flist) {
std::cout << i << " ";
}
std::cout << std::endl;
flist.clear();
return 0;
}
2.2 关联容器
set
#include <set>
#include <iostream>
int main() {
std::set<int> s;
s.insert(10);
s.insert(20);
s.insert(10);
s.insert(30);
std::set<int> s2 = {5, 15, 25};
std::set<int> s3(s.begin(), s.end());
std::cout << "Size: " << s.size() << std::endl;
auto it = s.find(20);
if (it != s.end()) {
std::cout << "Found: " << *it << std::endl;
}
s.erase(10);
s.erase(s.begin());
for (auto i : s) {
std::cout << i << " ";
}
std::cout << std::endl;
std::cout << "Count 20: " << s.count(20) << std::endl;
s.clear();
return 0;
}
map
#include <map>
#include <iostream>
#include <string>
int main() {
std::map<std::string, int> m;
m["apple"] = 100;
m["banana"] = 200;
m.insert({"cherry", 300});
std::map<std::string, int> m2 = {{"grape", 400}, {"orange", 500}};
std::cout << "apple: " << m["apple"] << std::endl;
auto it = m.find("banana");
if (it != m.end()) {
std::cout << "Found: " << it->first << " = " << it->second << std::endl;
}
m.erase("apple");
for (auto& pair : m) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
std::cout << "Size: " << m.size() << std::endl;
m.clear();
return 0;
}
multiset
#include <set>
#include <iostream>
int main() {
std::multiset<int> ms;
ms.insert(10);
ms.insert(20);
ms.insert(10);
ms.insert(30);
ms.insert(20);
std::cout << "Size: " << ms.size() << std::endl;
std::cout << "Count 10: " << ms.count(10) << std::endl;
auto range = ms.equal_range(20);
for (auto it = range.first; it != range.second; ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
ms.erase(ms.find(10));
for (auto i : ms) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
multimap
#include <map>
#include <iostream>
#include <string>
int main() {
std::multimap<std::string, int> mm;
mm.insert({"apple", 100});
mm.insert({"apple", 150});
mm.insert({"banana", 200});
mm.insert({"apple", 250});
std::cout << "Size: " << mm.size() << std::endl;
std::cout << "Count apple: " << mm.count("apple") << std::endl;
auto range = mm.equal_range("apple");
for (auto it = range.first; it != range.second; ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
mm.erase(mm.find("apple"));
for (auto& pair : mm) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
2.3 无序关联容器
unordered_set
#include <unordered_set>
#include <iostream>
int main() {
std::unordered_set<int> us;
us.insert(10);
us.insert(20);
us.insert(10);
us.insert(30);
std::cout << "Size: " << us.size() << std::endl;
auto it = us.find(20);
if (it != us.end()) {
std::cout << "Found: " << *it << std::endl;
}
us.erase(10);
for (auto i : us) {
std::cout << i << " ";
}
std::cout << std::endl;
std::cout << "Bucket count: " << us.bucket_count() << std::endl;
std::cout << "Load factor: " << us.load_factor() << std::endl;
us.clear();
return 0;
}
unordered_map
#include <unordered_map>
#include <iostream>
#include <string>
int main() {
std::unordered_map<std::string, int> um;
um["apple"] = 100;
um["banana"] = 200;
um.insert({"cherry", 300});
std::cout << "apple: " << um["apple"] << std::endl;
auto it = um.find("banana");
if (it != um.end()) {
std::cout << "Found: " << it->first << " = " << it->second << std::endl;
}
um.erase("apple");
for (auto& pair : um) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
std::cout << "Bucket count: " << um.bucket_count() << std::endl;
std::cout << "Load factor: " << um.load_factor() << std::endl;
um.clear();
return 0;
}
2.4 容器适配器
stack
#include <stack>
#include <iostream>
#include <vector>
int main() {
std::stack<int> st;
std::stack<int, std::vector<int>> st2;
st.push(10);
st.push(20);
st.push(30);
std::cout << "Top: " << st.top() << std::endl;
std::cout << "Size: " << st.size() << std::endl;
st.pop();
std::cout << "After pop, top: " << st.top() << std::endl;
while (!st.empty()) {
std::cout << st.top() << " ";
st.pop();
}
std::cout << std::endl;
return 0;
}
queue
#include <queue>
#include <iostream>
#include <list>
int main() {
std::queue<int> q;
std::queue<int, std::list<int>> q2;
q.push(10);
q.push(20);
q.push(30);
std::cout << "Front: " << q.front() << std::endl;
std::cout << "Back: " << q.back() << std::endl;
std::cout << "Size: " << q.size() << std::endl;
q.pop();
std::cout << "After pop, front: " << q.front() << std::endl;
while (!q.empty()) {
std::cout << q.front() << " ";
q.pop();
}
std::cout << std::endl;
return 0;
}
priority_queue
#include <queue>
#include <iostream>
#include <vector>
int main() {
std::priority_queue<int> pq;
std::priority_queue<int, std::vector<int>, std::greater<int>> pq_min;
pq.push(30);
pq.push(10);
pq.push(50);
pq.push(20);
std::cout << "Top: " << pq.top() << std::endl;
std::cout << "Size: " << pq.size() << std::endl;
pq.pop();
std::cout << "After pop, top: " << pq.top() << std::endl;
while (!pq.empty()) {
std::cout << pq.top() << " ";
pq.pop();
}
std::cout << std::endl;
pq_min.push(30);
pq_min.push(10);
pq_min.push(50);
while (!pq_min.empty()) {
std::cout << pq_min.top() << " ";
pq_min.pop();
}
std::cout << std::endl;
return 0;
}
三、迭代器(Iterators)
#include <vector>
#include <list>
#include <iostream>
#include <iterator>
int main() {
std::vector<int> v = {10, 20, 30, 40, 50};
std::vector<int>::iterator it;
for (it = v.begin(); it != v.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
std::vector<int>::reverse_iterator rit;
for (rit = v.rbegin(); rit != v.rend(); ++rit) {
std::cout << *rit << " ";
}
std::cout << std::endl;
std::list<int> lst = {1, 2, 3, 4, 5};
std::list<int>::const_iterator cit;
for (cit = lst.cbegin(); cit != lst.cend(); ++cit) {
std::cout << *cit << " ";
}
std::cout << std::endl;
auto it2 = std::next(v.begin(), 2);
std::cout << "Element at index 2: " << *it2 << std::endl;
auto it3 = std::prev(v.end(), 1);
std::cout << "Last element: " << *it3 << std::endl;
std::distance(v.begin(), v.end());
std::advance(it2, 1);
std::cout << "After advance: " << *it2 << std::endl;
return 0;
}
四、算法(Algorithms)
4.1 查找算法
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> v = {10, 20, 30, 40, 50, 30, 60};
auto it = std::find(v.begin(), v.end(), 30);
if (it != v.end()) {
std::cout << "Found at position: " << std::distance(v.begin(), it) << std::endl;
}
auto it2 = std::find_if(v.begin(), v.end(), [](int x) { return x > 40; });
if (it2 != v.end()) {
std::cout << "First element > 40: " << *it2 << std::endl;
}
auto it3 = std::find_if_not(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
int count = std::count(v.begin(), v.end(), 30);
std::cout << "Count of 30: " << count << std::endl;
int count_if = std::count_if(v.begin(), v.end(), [](int x) { return x > 20; });
std::cout << "Count of elements > 20: " << count_if << std::endl;
bool all_even = std::all_of(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
std::cout << "All even: " << (all_even ? "Yes" : "No") << std::endl;
bool any_odd = std::any_of(v.begin(), v.end(), [](int x) { return x % 2 != 0; });
std::cout << "Any odd: " << (any_odd ? "Yes" : "No") << std::endl;
bool none_negative = std::none_of(v.begin(), v.end(), [](int x) { return x < 0; });
std::cout << "None negative: " << (none_negative ? "Yes" : "No") << std::endl;
return 0;
}
4.2 排序和相关操作
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> v = {30, 10, 50, 20, 40};
std::sort(v.begin(), v.end());
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
std::sort(v.begin(), v.end(), std::greater<int>());
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
std::random_shuffle(v.begin(), v.end());
std::sort(v.begin(), v.end());
bool is_sorted = std::is_sorted(v.begin(), v.end());
std::cout << "Is sorted: " << (is_sorted ? "Yes" : "No") << std::endl;
std::reverse(v.begin(), v.end());
std::nth_element(v.begin(), v.begin() + 2, v.end());
std::cout << "3rd smallest element: " << v[2] << std::endl;
std::partial_sort(v.begin(), v.begin() + 3, v.end());
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
4.3 修改序列操作
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
std::vector<int> v2(5);
std::copy(v.begin(), v.end(), v2.begin());
std::fill(v.begin(), v.end(), 10);
std::fill_n(v2.begin() + 2, 3, 20);
std::generate(v.begin(), v.end(), []() { static int n = 0; return n++; });
std::generate_n(v2.begin(), 3, []() { static int n = 100; return n += 10; });
std::remove(v.begin(), v.end(), 2);
auto new_end = std::remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
v.erase(new_end, v.end());
std::replace(v.begin(), v.end(), 1, 100);
std::replace_if(v.begin(), v.end(), [](int x) { return x > 3; }, 200);
std::unique(v.begin(), v.end());
return 0;
}
4.4 数值算法
#include <vector>
#include <numeric>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
int sum = std::accumulate(v.begin(), v.end(), 0);
std::cout << "Sum: " << sum << std::endl;
int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());
std::cout << "Product: " << product << std::endl;
std::vector<int> v2 = {10, 20, 30, 40, 50};
int inner_product = std::inner_product(v.begin(), v.end(), v2.begin(), 0);
std::cout << "Inner product: " << inner_product << std::endl;
std::vector<int> result(v.size());
std::adjacent_difference(v.begin(), v.end(), result.begin());
std::partial_sum(v.begin(), v.end(), result.begin());
return 0;
}
4.5 集合算法
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> v1 = {1, 2, 3, 4, 5};
std::vector<int> v2 = {3, 4, 5, 6, 7};
std::vector<int> result;
result.resize(v1.size() + v2.size());
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
auto it = std::set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());
result.resize(it - result.begin());
std::cout << "Union: ";
for (auto i : result) {
std::cout << i << " ";
}
std::cout << std::endl;
result.clear();
result.resize(std::min(v1.size(), v2.size()));
it = std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());
result.resize(it - result.begin());
std::cout << "Intersection: ";
for (auto i : result) {
std::cout << i << " ";
}
std::cout << std::endl;
result.clear();
result.resize(v1.size());
it = std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());
result.resize(it - result.begin());
std::cout << "Difference (v1 - v2): ";
for (auto i : result) {
std::cout << i << " ";
}
std::cout << std::endl;
bool is_subset = std::includes(v2.begin(), v2.end(), v1.begin(), v1.end());
std::cout << "v1 is subset of v2: " << (is_subset ? "Yes" : "No") << std::endl;
return 0;
}
五、函数对象(Functors)
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
class Multiplier {
private:
int factor;
public:
Multiplier(int f) : factor(f) {}
int operator()(int x) const {
return x * factor;
}
};
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
Multiplier mult(10);
std::transform(v.begin(), v.end(), v.begin(), mult);
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
std::vector<int> v2 = {10, 20, 30, 40, 50};
std::transform(v.begin(), v.end(), v2.begin(), v.begin(), std::plus<int>());
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
std::sort(v.begin(), v.end(), std::greater<int>());
int count = std::count_if(v.begin(), v.end(), std::bind2nd(std::greater<int>(), 30));
std::cout << "Count > 30: " << count << std::endl;
auto func = [](int x) { return x * x; };
std::transform(v.begin(), v.end(), v.begin(), func);
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
六、适配器(Adapters)
6.1 函数适配器
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
std::transform(v.begin(), v.end(), v.begin(), std::bind1st(std::multiplies<int>(), 10));
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
auto is_even = std::bind2nd(std::modulus<int>(), 2);
int count_even = std::count_if(v.begin(), v.end(), [&is_even](int x) { return is_even(x) == 0; });
std::cout << "Even numbers: " << count_even << std::endl;
std::sort(v.begin(), v.end(), std::not2(std::less<int>()));
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
6.2 迭代器适配器
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
std::vector<int> v2;
std::back_insert_iterator<std::vector<int>> back_it(v2);
std::copy(v.begin(), v.end(), back_it);
std::front_insert_iterator<std::vector<int>> front_it(v2);
std::insert_iterator<std::vector<int>> insert_it(v2, v2.begin() + 2);
std::copy(v.begin(), v.end(), insert_it);
for (auto i : v2) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
七、分配器(Allocators)
#include <vector>
#include <iostream>
#include <memory>
template <typename T>
class CustomAllocator {
public:
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
template <typename U>
struct rebind {
using other = CustomAllocator<U>;
};
CustomAllocator() noexcept {}
template <typename U>
CustomAllocator(const CustomAllocator<U>&) noexcept {}
pointer allocate(size_type n) {
if (n > max_size()) {
throw std::bad_alloc();
}
return static_cast<pointer>(::operator new(n * sizeof(T)));
}
void deallocate(pointer p, size_type) noexcept {
::operator delete(p);
}
size_type max_size() const noexcept {
return std::numeric_limits<size_type>::max() / sizeof(T);
}
};
template <typename T, typename U>
bool operator==(const CustomAllocator<T>&, const CustomAllocator<U>&) {
return true;
}
template <typename T, typename U>
bool operator!=(const CustomAllocator<T>&, const CustomAllocator<U>&) {
return false;
}
int main() {
std::vector<int, CustomAllocator<int>> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
for (auto i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
八、STL容器性能比较
8.1 容器操作复杂度
| 操作 | vector | list | deque | set | map | unordered_set | unordered_map |
|---|---|---|---|---|---|---|---|
| 插入(尾部) | O(1)均摊 | O(1) | O(1)均摊 | O(log n) | O(log n) | O(1)均摊 | O(1)均摊 |
| 插入(头部) | O(n) | O(1) | O(1) | O(log n) | O(log n) | O(1)均摊 | O(1)均摊 |
| 插入(中间) | O(n) | O(1) | O(n) | O(log n) | O(log n) | O(1)均摊 | O(1)均摊 |
| 删除(尾部) | O(1) | O(1) | O(1) | O(log n) | O(log n) | O(1)均摊 | O(1)均摊 |
| 删除(头部) | O(n) | O(1) | O(1) | O(log n) | O(log n) | O(1)均摊 | O(1)均摊 |
| 删除(中间) | O(n) | O(1) | O(n) | O(log n) | O(log n) | O(1)均摊 | O(1)均摊 |
| 查找 | O(n) | O(n) | O(n) | O(log n) | O(log n) | O(1)均摊 | O(1)均摊 |
| 随机访问 | O(1) | O(n) | O(1) | O(log n) | O(log n) | O(n) | O(n) |
8.2 容器选择指南
- 需要频繁随机访问:vector, array
- 需要频繁在两端操作:deque
- 需要频繁在任意位置插入/删除:list
- 需要高效查找且保持有序:set, map
- 需要最高效的查找:unordered_set, unordered_map
- 需要后进先出操作:stack
- 需要先进先出操作:queue
- 需要优先级操作:priority_queue
九、STL使用最佳实践
- 选择合适的容器:根据操作需求选择性能最优的容器
- 使用迭代器而非索引:提高代码的通用性和效率
- 优先使用STL算法:避免重复造轮子
- 使用auto简化代码:减少类型声明的复杂性
- 注意容器的内存管理:避免不必要的内存分配
- 使用移动语义提高性能:减少不必要的复制
- 合理使用lambda表达式:简化函数对象的使用
- 注意异常安全:确保操作的原子性
- 避免频繁的容器重建:优先使用clear()而非重新创建
- 使用emplace相关函数:直接在容器中构造对象