C++11 新增 STL 容器
重点掌握:std::array(静态数组)、std::forward_list(单向链表)、unordered系列(哈希容器)
1. std::array 安全静态数组
核心特点:
1.封装原生栈静态数组,大小编译期固定,不占用堆内存;
2.完美替代原生数组:不退化、支持边界检查、自带size()、兼容所有 STL 算法;
3.头文件:<array>
代码示例:
#include <iostream> #include <array> #include <algorithm> using namespace std; int main() { // 格式:array<类型, 固定大小> array<int, 5> arr = {1,3,2,5,4}; // 安全访问:at()越界抛异常,[]不检查(原生数组的缺点) arr.at(0) = 10; // arr.at(10) = 0; 越界直接报错,避免内存非法访问 // 支持STL算法+范围for遍历 sort(arr.begin(), arr.end()); for(int x : arr) cout << x << " "; // 2 3 4 5 10 return 0; }2. std::forward_list 轻量单向链表
核心特点:
1.C++11 专为节约内存设计的单向链表;
2.对比std::list(双向链表):更省空间、仅支持前置迭代器、无 size ()(保证头插 / 删 O (1) 效率);
3.头文件:<forward_list>
代码示例:
#include <iostream> #include <forward_list> using namespace std; int main() { forward_list<int> fl = {1,2,3}; fl.push_front(0); // 头插O(1),核心优势 fl.insert_after(fl.begin(), 5); // 单向链表:只能在节点后插入 for(int x : fl) cout << x << " "; // 0 5 1 2 3 return 0; }3. unordered 系列 哈希容器
核心特点:
包含:unordered_map/unordered_set/unordered_multimap/unordered_multiset;
底层哈希表,无序,平均查询 / 插入 / 删除 O(1)(远快于 map/set 的 O (logn));
1.对比 map/set(红黑树):查询更快,但无序;
2.头文件:<unordered_map>/<unordered_set>
代码示例:
#include <iostream> #include <unordered_map> using namespace std; int main() { unordered_map<string, int> umap; umap["张三"] = 18; umap["李四"] = 20; // 遍历无序 for(auto& p : umap) { cout << p.first << ":" << p.second << endl; } return 0; }