STL标准库
学习C++标准模板库的容器、算法和迭代器
68%
容器
算法
迭代器
STL容器
顺序容器
包括 vector、list、deque 等顺序存储的容器。
#include <vector>
#include <list>
#include <deque>
using namespace std;
int main() {
// vector示例
vector<int> vec = {1, 2, 3, 4, 5};
vec.push_back(6); // 在末尾添加元素
vec.pop_back(); // 删除末尾元素
cout << vec.front() << endl; // 访问第一个元素
cout << vec.back() << endl; // 访问最后一个元素
// list示例(双向链表)
list<string> lst = {"C++", "Java", "Python"};
lst.push_front("Rust"); // 在开头添加元素
lst.push_back("Go"); // 在末尾添加元素
// deque示例(双端队列)
deque<double> dq;
dq.push_front(1.1); // 在开头添加元素
dq.push_back(2.2); // 在末尾添加元素
// 使用迭代器遍历
for(const auto& item : vec) {
cout << item << " ";
}
cout << endl;
// 使用迭代器修改元素
for(auto it = lst.begin(); it != lst.end(); ++it) {
cout << *it << " ";
}
cout << endl;
}
关联容器
包括 set、map、multiset、multimap 等基于键值对的容器。
#include <map>
#include <set>
using namespace std;
int main() {
// map示例(键值对容器)
map<string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 89;
scores["Charlie"] = 92;
// 检查键是否存在
if(scores.find("Alice") != scores.end()) {
cout << "Alice's score: " << scores["Alice"] << endl;
}
// 遍历map
for(const auto& [name, score] : scores) {
cout << name << ": " << score << endl;
}
// set示例(有序集合)
set<int> numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5}; // 自动去重和排序
numbers.insert(7);
// 检查元素是否存在
if(numbers.count(5) > 0) {
cout << "5 exists in the set" << endl;
}
// multimap示例(允许重复键)
multimap<string, string> dictionary;
dictionary.insert({"apple", "一种水果"});
dictionary.insert({"apple", "一个科技公司"});
// 查找所有相同键的值
auto range = dictionary.equal_range("apple");
for(auto it = range.first; it != range.second; ++it) {
cout << it->first << ": " << it->second << endl;
}
}
- 顺序容器适合按位置访问和修改元素
- 关联容器适合需要快速查找的场景
- 所有容器都支持迭代器操作
- 不同容器在性能和功能上各有优势