大家好本篇带你一次性吃透 C STL 常用容器从用法到场景全部用代码讲清楚新手也能直接上手用。一、什么是 STLSTLStandard Template Library是 C 标准模板库提供了常用数据结构与算法让我们不用重复造轮子。STL 容器主要分为三大类顺序容器vector、list、deque、array关联容器map、unordered_map、set、unordered_set容器适配器stack、queue下面只讲最常用、最常考的容器。二、顺序容器 —— 最常用1. vector动态数组最常用容器支持随机访问尾部增删快。常用操作#include vector using namespace std; vectorint v; // 增 v.push_back(10); v.push_back(20); // 查 cout v[0] endl; cout v.at(1) endl; // 遍历 for (auto x : v) cout x ; // 大小与容量 v.size(); v.empty(); // 删除最后一个元素 v.pop_back(); // 清空 v.clear();适用场景需要随机访问尾部快速增删最常用、优先选择2. string字符串本质是存放 char 的容器非常常用。#include string string s hello; s world; s.size(); s.substr(0,3); // 取子串 s.find(lo); // 查找三、关联容器 —— 键值对 / 去重1. map有序键值对key 唯一自动排序底层红黑树。#include map mapint, string mp; mp[1] 张三; mp[2] 李四; // 遍历 for (auto p : mp) { cout p.first p.second endl; }2. unordered_map哈希表无序、查找更快 O (1)最爱用。#include unordered_map unordered_mapint, string ump; ump[1001] Tom;map和unordered_map的区别map有序、查找 O (log n)unordered_map无序、查找 O (1)更快3. set去重 有序自动去重、自动排序。setint st; st.insert(3); st.insert(1); st.insert(3); // 自动去重四、容器适配器 —— 栈、队列1. stack栈先进后出 FILOstackint st; st.push(10); st.top(); // 取栈顶 st.pop(); // 删除栈顶2. queue队列先进先出 FIFOqueueint q; q.push(10); q.front(); q.pop();五、容器怎么选超实用新手秒懂选择指南需要数组、随机访问 →vector需要字符串 →string需要键值对、快速查找 →unordered_map需要有序键值对 →map需要去重 →set先进后出 →stack先进先出 →queue六、完整示例代码可直接运行#include iostream #include vector #include string #include map #include unordered_map #include set #include stack #include queue using namespace std; int main() { // vector vectorint v {1,2,3}; v.push_back(4); cout vector: ; for (auto x : v) cout x ; cout endl; // string string s STL; cout string: s endl; // unordered_map unordered_mapint, string mp; mp[10] Java; mp[20] C; cout map: mp[20] endl; // set setint st {3,1,4,1,3}; cout set: ; for (auto x : st) cout x ; cout endl; // stack stackint sk; sk.push(100); cout stack top: sk.top() endl; return 0; }全文完~关注互关