C++ STL容器vector map set使用详解与性能分析及常见问题解决

引言
在C++标准模板库(STL)中,vector、map和set是最常用且功能强大的容器。它们分别代表了动态数组、键值对映射和集合数据结构。本文将深入探讨这三个容器的使用方法、性能特点以及在实际开发中可能遇到的问题及其解决方案。
1. vector容器详解
1.1 vector的基本概念
vector是一个动态数组,它在内存中是连续存储的。这使得vector在随机访问方面非常高效,时间复杂度为O(1)。然而,在中间插入或删除元素时,可能需要移动大量元素,效率较低。
1.2 vector的常用操作
1.2.1 创建和初始化
#include
#include

int main() {
// 默认构造函数
std::vector vec1;

// 指定大小
std::vector vec2(5); // 5个元素,每个初始化为0

// 指定大小和初始值
std::vector vec3(5, 10); // 5个元素,每个初始化为10

// 使用初始化列表
std::vector vec4 = {1, 2, 3, 4, 5};

// 拷贝构造
std::vector vec5(vec4);

// 迭代器范围构造
std::vector vec6(vec4.begin(), vec4.begin() + 3);

return 0;
}
1.2.2 添加元素
#include
#include

int main() {
std::vector vec;

// push_back: 在末尾添加元素
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);

// emplace_back: 在末尾构造元素(避免拷贝)
vec.emplace_back(4);
vec.emplace_back(5);

// insert: 在指定位置插入元素
vec.insert(vec.begin(), 0); // 在开头插入0
vec.insert(vec.begin() + 2, 99); // 在索引2处插入99

// insert: 插入多个相同元素
vec.insert(vec.begin() + 3, 3, 88); // 插入3个88

// insert: 插入另一个vector的部分
std::vector vec2 = {10, 20, 30};
vec.insert(vec.end(), vec2.begin(), vec2.end());

// 输出结果
for (int num : vec) {
std::cout << num << " "; } std::cout << std::endl; return 0; } 1.2.3 删除元素 #include
#include
#include

int main() {
std::vector vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// pop_back: 删除最后一个元素
vec.pop_back();

// erase: 删除指定位置的元素
vec.erase(vec.begin() + 2); // 删除索引2的元素

// erase: 删除范围内的元素
vec.erase(vec.begin(), vec.begin() + 2); // 删除前两个元素

// remove和erase结合使用:删除特定值的元素
vec.push_back(5);
vec.push_back(5);
vec.erase(std::remove(vec.begin(), vec.end(), 5), vec.end());

// clear: 清空所有元素
// vec.clear();

// 输出结果
for (int num : vec) {
std::cout << num << " "; } std::cout << std::endl; return 0; } 1.2.4 访问元素 #include
#include

int main() {
std::vector vec = {1, 2, 3, 4, 5};

// 使用下标访问
std::cout << "vec[2] = " << vec[2] << std::endl; // 使用at访问(会进行边界检查) std::cout << "vec.at(2) = " << vec.at(2) << std::endl; // 访问第一个和最后一个元素 std::cout << "front() = " << vec.front() << std::endl; std::cout << "back() = " << vec.back() << std::0dendl; // 使用迭代器访问 std::vector::iterator it;
for (it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " "; } std::cout << std::endl; // 使用范围for循环(C++11) for (const auto& num : vec) { std::cout << num << " "; } std::cout << std::endl; return 0; } 1.2.5 容量和大小管理 #include
#include

int main() {
std::vector vec = {1, 2, 3, 4, 5};

// size: 当前元素个数
std::cout << "size: " << vec.size() << std::endl; // capacity: 当前分配的内存能容纳的元素个数 std::cout << "capacity: " << vec.capacity() << std::0dendl; // empty: 判断是否为空 std::cout << "empty: " << (vec.empty() ? "true" : "false") << std::endl; // resize: 改变大小 vec.resize(8); // 增加到8个元素,新增的元素初始化为0 std::cout << "After resize(8): size=" << vec.size() << ", capacity=" << vec.capacity() << std::endl; vec.resize(3); // 缩小到3个元素 std::cout << "After resize(3): size=" << vec.size() << ", capacity=" << vec.capacity() << std::endl; // reserve: 预留空间(只改变capacity,不改变size) vec.reserve(20); std::cout << "After reserve(20): size=" << vec.size() << ", capacity=" << vec.capacity() << std::endl; // shrink_to_fit: 释放多余的内存(C++11) vec.shrink_to_fit(); std::cout << "After shrink_to_fit: size=" << vec.size() << ", capacity=" << vec.capacity() << std::endl; return 0; } 1.3 vector的性能分析 1.3.1 时间复杂度 随机访问 : O(1) 末尾插入/删除 : 平均O(1)(当capacity足够时),最坏O(n)(需要重新分配内存) 中间插入/删除 : O(n)(需要移动元素) 查找 : O(n)(线性查找) 1.3.2 内存管理 vector的内存增长策略通常是翻倍(或1.5倍)。当size达到capacity时,会: 分配一块更大的内存(通常是当前capacity的2倍) 将原有元素拷贝(或移动)到新内存 释放旧内存 这种策略保证了平均O(1)的尾部插入性能,但会导致内存浪费和拷贝开销。 1.3.3 性能优化建议 预分配内存 : 如果知道大致大小,使用 reserve() 预分配内存 使用emplace_back : 避免不必要的拷贝/移动 删除元素时使用erase-remove惯用法 : 避免多次移动 考虑使用std::list或std::deque : 如果需要频繁在中间插入删除 1.4 vector常见问题及解决方案 1.4.1 迭代器失效问题 #include
#include

int main() {
std::vector vec = {1, 2, 3, 4, 5};

// 错误示例:在遍历过程中删除元素会导致迭代器失效
// for (auto it = vec.begin(); it != vec.end(); ++it) {
// if (*it % 2 == 0) {
// vec.erase(it); // 这里it会失效!
// }
// }

// 正确做法1:使用erase返回值
for (auto it = vec.begin(); it != vec.end(); ) {
if (*it % 2 == 0) {
it = vec.erase(it); // erase返回下一个有效的迭代器
} else {
++it;
}
}

// 正确做法2:使用remove-erase惯用法
vec = {1, 2, 3, 4, 5};
vec.erase(std::remove_if(vec.begin(), vec.end(), [](int x) { return x % 2 == 0; }), vec.end());

// 正确做法3:使用反向迭代器
vec = {1, 2, 3, 4, 5};
for (auto it = vec.rbegin(); it != vec.rend(); ) {
if (*it % 2 == 0) {
// 注意:erase接受反向迭代器需要转换
it = std::reverse_iterator(vec.erase(std::next(it).base()));
} else {
++it;
}
}

return 0;
}
1.4.2 内存泄漏与性能问题
#include
#include
#include

class HeavyObject {
public:
HeavyObject() { std::cout << "构造\n"; } HeavyObject(const HeavyObject&) { std::cout << "拷贝构造\n"; } HeavyObject(HeavyObject&&) noexcept { std::cout << "移动构造\n"; } ~HeavyObject() { std::cout << "析构\n"; } }; int main() { std::vector vec;

// 错误做法:多次重新分配内存
for (int i = 0; i < 10; ++i) { vec.push_back(HeavyObject()); // 每次都可能触发重新分配和拷贝 } // 正确做法:预分配内存 vec.clear(); vec.reserve(10); for (int i = 0; i < 10; ++i) { vec.emplace_back(); // 使用emplace_back避免临时对象的拷贝 } return 0; } 1.4.3 越界访问问题 #include
#include

int main() {
std::vector vec = {1, 2, 3};

// 使用[]越界是未定义行为,可能导致程序崩溃或数据损坏
// std::cout << vec[10] << std::endl; // 危险! // 使用at()会抛出std::out_of_range异常 try { std::cout << vec.at(10) << std::std::endl; } catch (const std::out_of_range& e) { std::cout << "越界访问: " << e.what() << std::endl; } // 安全访问 if (vec.size() > 10) {
std::cout << vec[10] << std::std::endl; } else { std::cout << "索引越界" << std::endl; } return 0; } 1.4.4 自定义类型的vector使用 #include
#include
#include

class Person {
private:
std::string name;
int age;
public:
Person(const std::string& n, int a) : name(n), age(a) {}

// 必须提供默认构造函数(如果需要空vector或resize)
Person() : name(“”), age(0) {}

// 拷贝构造函数和赋值运算符(如果需要深拷贝)
Person(const Person& other) : name(other.name), age(other.type) {}
Person& operator=(const Person& other) {
if (this != &other) {
name = other.name;
age = other.age;
}
return *this;
}

// 移动构造函数和移动赋值运算符(C++11,提高性能)
Person(Person&& other) noexcept : name(std::move(other.name)), age(other.age) {}
Person& operator=(Person&& other) noexcept {
if (this != &other) {
name = std::move(other.name);
age = other.age;
}
return *this;
}

// 用于排序的比较运算符
bool operator<(const Person& other) const { return age < other.age; } // 用于输出 friend std::ostream& operator<<(std::ostream& os, const Person& p) { os << p.name << "(" << p.age << ")"; return os; } }; int main() { std::vector people;

// 使用emplace_back直接构造
people.emplace_back(“Alice”, 25);
people.emplace_back(“Bob”, 30);
people.emplace_back(“Charlie”, 22);

// 排序
std::sort(people.begin(), people.end());

// 输出
for (const auto& p : people) {
std::cout << p << " "; } std::cout << std::endl; return 0; } 2. map容器详解 2.1 map的基本概念 map是关联容器,存储键值对(key-value),基于红黑树实现(平衡二叉搜索树)。所有元素按键的顺序自动排序,键是唯一的。查找、插入、删除的时间复杂度都是O(log n)。 2.2 map的常用操作 2.2.1 创建和初始化 #include #include
#include

int main() {
// 默认构造
std::map m1;

// 使用初始化列表(C++11)
std::map m2 = {
{1, “one”},
{2, “two”},
{3, “three”}
};

// 使用迭代器范围
std::map m3(m2.begin(), m2.end());

// 拷贝构造
std::map m4(m3);

// 自定义比较器(按值降序)
std::map> m5 = {
{1, “one”},
{2, “two”}
};

return 0;
}
2.2.2 插入元素
#include

#include
#include

int main() {
std::map m;

// 方法1: 使用insert插入pair
m.insert(std::make_pair(1, “one”));
m.insert({2, “two”});

// 方法2: 使用insert返回值
auto result = m.insert({3, “three”});
if (result.second) {
std::cout << "插入成功,键: " << result.first->first << std::endl; } else { std::cout << "插入失败,键已存在" << std::endl; } // 方法3: 使用operator[](如果键不存在会自动创建) m[4] = "four"; m[5] = "five"; // 方法4: 使用emplace(避免拷贝) m.emplace(6, "six"); m.emplace(7, "seven"); // 方法5: insert_or_assign (C++17) m.insert_or_assign(8, "eight"); // 如果存在则覆盖 m.insert_or_assign(1, "ONE"); // 覆盖已存在的键1 // 方法6: try_emplace (C++17) auto [it, inserted] = m.try_emplace(9, "nine"); if (inserted) { std::cout << "键9插入成功" << std::endl; } // 输出所有元素 for (const auto& [key, value] : m) { std::cout << key << " => ” << value << std::endl; } return 0; } 2.2.3 查找元素 #include #include
#include

int main() {
std::map m = {
{1, “one”},
{2, “two”},
{3, “3”}
};

// 方法1: 使用find(返回迭代器)
auto it = m.find(2);
if (it != m.end()) {
std::cout << "找到: " << it->first << " => ” << it->second << std::std::endl; } else { std::cout << "未找到" << std::endl; } // 方法2: 使用count(返回0或1) if (m.count(3)) { std::cout << "键3存在" << std::endl; } // 方法3: 使用operator[](危险!如果键不存在会创建) // std::cout << m[10] << std::endl; // 会创建键10,值为空字符串 // 方法4: 使用at(C++11,键不存在抛出异常) try { std::cout << m.at(2) << std::endl; } catch (const std::out_of_range& e) { std::cout << "键不存在" << std::endl; return 1; } // 方法5: 使用contains(C++20) if (m.contains(1)) { std::cout << "包含键1" << std::std::endl; } return 0; } 2.2.4 删除元素 #include #include
#include

int main() {
std::map m = {
{1, “one”},
2, “two”},
{3, “3”},
{4, “four”},
{5, “five”}
};

// 方法1: 使用erase(key)
size_t n = m.erase(3); // 返回删除的元素个数(0或1)
std::cout << "删除了 " << n << " 个元素" << std::endl; // 方法2: 使用erase(iterator) auto it = m.find(4); if (it != m.end()) { m.erase(it); } // 方法3: 使用erase(range) m.erase(m.begin(), std::next(m.begin(), 2)); // 删除前两个元素 // 方法4: 使用clear // m.clear(); // 输出剩余元素 for (const auto& [key, value] : m) { std::cout << key << " => ” << value << std::endl; } return 0; } 2.2.5 遍历和访问 #include #include
#include

int main() {
std::map m = {
{1, “one”},
{2, “two”},
{3, “three”}
};

// 方法1: 使用迭代器
for (auto it = m.begin(); it != m.end(); ++it) {
std::cout << it->first << " => ” << it->second << std::endl; } // 方法2: 使用范围for循环(C++11) for (const auto& [key, value] : m) { std::cout << key << " => ” << value << std::endl; } // 方法3: 反向遍历 for (auto it = m.rbegin(); it != m.rend(); ++it) { std::cout << it->first << " => ” << it->second << std::endl; } // 方法4: 只遍历键 for (const auto& pair : m) { std::cout << pair.first << " "; } std::cout << std::endl; // 方法5: 只遍历值 for (const auto& pair : map) { std::cout << pair.second << " "; } std::cout << std::endl; return 0; } 2.3 map的性能分析 2.3.1 时间复杂度 查找 : O(log n) 插入 : O(log n) 删除 : O(log n) 遍历 : O(n) 2.3.2 内存布局 map基于红黑树,每个节点包含: 键 值 指向父节点、左子节点、右子节点的指针 颜色信息(红/黑) 因此,map的内存开销较大,每个元素需要额外的指针开销。 2.3.3 与unordered_map的对比 特性 map unordered_map 实现 红黑树 哈希表 排序 自动按键排序 无序 查找 O(log n) 平均O(1),最坏O(n) 内存 较大(指针开销) 较小(但可能有哈希冲突) 迭代器 双向迭代器 前向迭代器 键要求 可比较(operator<) 可哈希且可相等 2.4 map常见问题及解决方案 2.4.1 operator[]的陷阱 #include #include

int main() {
std::map m;

// 陷阱1: 使用operator[]查找不存在的键会创建空元素
std::cout << "Size before: " << m.size() << std::endl; std::cout << m[10] << std::endl; // 创建了键10,值为空字符串 std::cout << "Size after: " << m.size() << std::endl; // 陷阱2: const map不能使用operator[] const std::map cm = {{1, “one”}};
// std::cout << cm[1] << std::endl; // 编译错误! std::cout << cm.at(1) << std::endl; // 正确 // 解决方案:使用find或at auto it = m.find(10); if (it != m.end()) { std::cout << "找到: " << it->second << std::endl; } else { std::cout << "未找到" << std::endl; } return 0; } 2.4.2 自定义键类型 #include #include
#include

// 自定义键类型
struct Point {
int x, y;

// 必须提供operator<用于排序 bool operator<(const Point& other) const { if (x != other.x) return x < other.x; return y < other.y; } }; // 或者使用自定义比较器 struct PointCompare { bool operator()(const Point& a, const Point& b) const { if (a.x != b.x) return a.x < b.x; return a.y < b.y; } }; int main() { // 使用默认的operator< std::map m1;
m1[{1, 2}] = “point1”;
m1[{2, 1}] = “point2”;

// 使用自定义比较器
std::map m2;
m2[{1, 2}] = “point1”;
m2[{2, 1}] = “point2”;

// 输出
for (const auto& [point, label] : m2) {
std::cout << "(" << point.x << "," << point.y << ") => ” << label << std::endl; } return 0; } 2.4.3 多重映射(multimap) #include #include
#include

int main() {
// multimap允许键重复
std::multimap mm;

mm.insert({1, “one”});
mm.insert({1, “ONE”});
mm.insert({2, “two”});

// 查找键1的所有值
auto range = mm.equal_range(1);
for (auto it = range.first; it != range.second; ++it) {
std::cout << it->first << " => ” << it->second << std::std::endl; } // 使用count统计键出现次数 std::cout << "键1出现了 " << mm.count(1) << " 次" << std::endl; return 0; } 2.4.4 性能优化技巧 #include #include
#include
#include

int main() {
const int N = 100000;

// 未优化版本:频繁重新分配内存
auto start = std::chrono::high_resolution_clock::now();
std::map m1;
for (int i = 0; i < N; ++i) { m1[i] = std::to_string(i); // 每次都可能重新分配 } auto end = std::chrono::high_resolution_clock::now(); std::cout << "未优化: " << std::chrono::duration(end – start).count() << "s" << std::endl; // 优化版本:使用emplace和reserve(虽然map没有reserve,但可以预分配) start = std::chrono::high_resolution_clock::now(); std::map m2;
// map没有reserve,但可以使用hint
for (int i = 0; i < N; ++i) { m2.emplace(i, std::to_string(i)); // 使用emplace避免拷贝 } end = std::chrono::high_resolution_clock::now(); std::cout << "优化后: " << std::chrono::duration(end – start).count() << "s" << std::endl; return 0; } 3. set容器详解 3.1 set的基本概念 set是关联容器,存储唯一的元素,基于红黑树实现。所有元素自动排序,查找、插入、删除的时间复杂度都是O(log n)。 3.2 set的常用操作 3.2.1 创建和初始化 #include
#include

int main() {
// 默认构造
std::set s1;

// 初始化列表
std::set s2 = {1, 2, 3, 4, 5, 3}; // 重复元素会被忽略

// 使用迭代器范围
std::vector vec = {5, 4, 3, 2, 1};
std::set s3(vec.begin(), vec.end());

// 自定义排序(降序)
std::set> s4 = {1, 2, 3, 4, 5};

return 0;
}
3.2.2 插入和删除
#include
#include

int main() {
std::set s;

// 插入单个元素
s.insert(3);
s.insert(1);
s.insert(4);
s.insert(2);

// 插入多个元素
s.insert({5, 6, 7});

// 使用emplace
s.emplace(8);

// 插入并获取结果
auto result = s.insert(3); // 重复插入
if (result.second) {
std::cout << "插入成功" << std::endl; } else { std::cout << "插入失败,元素已存在" << std::endl; } // 删除元素 s.erase(3); // 按值删除 s.erase(s.find(4)); // 按迭代器删除 // 输出 for (int num : s) { std::cout << num << " "; } std::cout << std::endl; return 0; } 3.2.3 查找和计数 #include
#include

int main() {
std::set s = {1, 2, 3, 4, 5};

// 查找
auto it = s.find(3);
if (it != s.end()) {
std::cout << "找到: " << *it << std::endl; } // 计数(0或1) if (s.count(3)) { std::cout << "元素3存在" << std::endl; } // 检查包含(C++20) if (s.contains(3)) { std::cout << "包含元素3" << std::std::endl; } // lower_bound和upper_bound auto lb = s.lower_bound(3); // >=3
auto ub = s.upper_bound(3); // >3
std::cout << "lower_bound(3): " << *lb << std::endl; std::cout << "upper_bound(3): " << *ub << std::endl; // equal_range auto range = s.equal_range(3); std::cout << "equal_range(3): [" << *range.first << ", " << *range.second << ")" << std::endl; return 0; } 3.2.4 集合运算 #include
#include
#include

int main() {
std::set s1 = {1, 2, 3, 4, 5};
std::set s2 = {4, 5, 6, 7, 8};

// 并集
std::set union_set;
std::set_union(s1.begin(), s1.end(), s2.begin(), s2.end(),
std::inserter(union_set, union_set.begin()));
std::cout << "并集: "; for (int num : union_set) std::cout << num << " "; std::cout << std::endl; // 交集 std::set intersect_set;
std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
std::inserter(intersect_set, intersect_set.begin()));
std::cout << "交集: "; for (int num : intersect_set) std::cout << num << " "; std::cout << std::endl; // 差集 std::set diff_set;
std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
std::inserter(diff_set, diff_set.begin()));
std::cout << "差集: "; for (int num : diff_set) std::cout << num << " "; std::cout << std::endl; // 对称差集 std::set symdiff_set;
std::set_symmetric_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
std::inserter(symdiff_set, symdiff_set.begin()));
std::cout << "对称差集: "; for (int num : symdiff_set) std::cout << num << " "; std::cout << std::endl; return 0; } 3.3 set的性能分析 3.3.1 时间复杂度 查找 : O(log n) 插入 : O(log n) 删除 : O(log n) 遍历 : O(n) 3.3.2 内存布局 与map类似,set也是基于红黑树,每个节点包含元素值、三个指针和颜色信息。 3.3.3 与unordered_set的对比 特性 set unordered_set 实现 红黑树 哈希表 排序 自动排序 无序 查找 O(log n) 平均O(1),最坏O(n) 内存 较大(指针开销) 较小(但可能有哈希冲突) 迭代器 双向迭代器 前向迭代器 元素要求 可比较(operator<) 可哈希且可相等 3.4 set常见问题及解决方案 3.4.1 元素修改问题 #include
#include

int main() {
// 错误:set的元素是const的,不能直接修改
std::set s = {1, 2, 3};
// *s.begin() = 10; // 编译错误!

// 正确做法:删除后重新插入
auto it = s.find(2);
if (it != s.end()) {
int old_value = *it;
s.erase(it);
s.insert(old_value * 10);
}

// 对于自定义类型,使用mutable成员
struct Point {
int x, y;
mutable int count; // 可以修改
bool operator<(const Point& other) const { return x < other.x; } }; std::set points;
points.insert({1, 2, 0});

auto pt_it = points.find({1, 2, 0});
if (pt_it != points.end()) {
pt_it->count++; // 可以修改mutable成员
}

return 0;
}
3.4.2 自定义排序规则
#include
#include
#include

// 自定义类型
struct Person {
std::string name;
int age;
};

// 自定义比较器(按年龄排序)
struct PersonCompare {
bool operator()(const Person& a, const Person& b) const {
return a.age < b.age; } }; int main() { std::set people;

people.insert({“Alice”, 25});
people.insert({“Bob”, 30});
// 注意:插入相同年龄的元素会被视为重复
people.insert({“Charlie”, 25}); // 这个不会被插入

// 输出
for (const auto& p : people) {
std::cout << p.name << "(" << p.age << ") "; } std::cout << std::endl; return 0; } 3.4.3 multiset的使用 #include
#include

int main() {
// multiset允许重复元素
std::multiset ms;

ms.insert(3);
ms.insert(1);
ms.insert(3); // 允许重复
ms.insert(2);
ms.insert(3);

// 统计元素出现次数
std::cout << "3出现了 " << ms.count(3) << " 次" << std::endl; // 删除所有3 ms.erase(3); // 输出 for (int num : ms) { std::cout << num << " "; } std::cout << std::endl; return 0; } 3.4.4 性能优化技巧 #include
#include
#include
#include

int main() {
const int N = 100000;

// 未优化:逐个插入
auto start = std::chrono::high_resolution_clock::now();
std::set s1;
for (int i = 0; i < N; ++i) { s1.insert(i); } auto end = std::chrono::high_resolution_clock::now(); std::cout << "逐个插入: " << std::chrono::duration(end – start).count() << "s" << std::endl; // 优化:使用范围插入 start = std::chrono::high_resolution_clock::now(); std::vector vec(N);
for (int i = 0; i < N; ++i) vec[i] = i; std::set s2;
s2.insert(vec.begin(), vec.end());
end = std::chrono::high_resolution_clock::now();
std::cout << "范围插入: " << std::chrono::duration(end – start).count() << "s" << std::endl; return 0; } 4. 综合比较与选择指南 4.1 何时使用vector 需要随机访问元素 主要在末尾添加/删除元素 元素数量相对稳定或可预测 需要连续内存布局(如与C API交互) 内存使用效率要求高 4.2 何时使用map 需要按键查找、插入、删除 需要保持元素按键排序 键是唯一的 需要O(log n)的查找性能 需要双向迭代器 4.3 何时使用set 需要存储唯一元素 需要快速判断元素是否存在 需要保持元素排序 需要集合运算(并集、交集等) 需要O(log n)的查找性能 4.4 性能对比总结 操作 vector map set 随机访问 O(1) - - 查找 O(n) O(log n) O(log n) 末尾插入 O(1) O(log n) O(log n) 中间插入 O(n) O(log n) O(log n) 删除 O(n) O(log n) O(log n) 内存开销 最小 较大 较大 缓存友好 是 否 否 4.5 实际应用案例 案例1:学生成绩管理系统 #include #include
#include
#include
#include

class GradeSystem {
private:
std::map grades; // 学号 -> 成绩

public:
void addGrade(const std::string& id, int grade) {
grades[id] = grade;
}

int getGrade(const std::string& id) const {
auto it = grades.find(id);
if (it != grades.end()) {
return it->second;
}
return -1; // 未找到
}

void printAll() const {
for (const auto& [id, grade] : grades) {
std::cout << id << ": " << grade << std::endl; } } // 按成绩排序输出 void printByGrade() const { std::vector> sorted_grades(grades.begin(), grades.end());
std::sort(sorted_grades.begin(), sorted_grades.end(),
[](const auto& a, const auto& b) { return a.second > b.second; });

for (const auto& [id, grade] : sorted_grades) {
std::cout << id << ": " << grade << std::endl; } } }; int main() { GradeSystem gs; gs.addGrade("001", 85); gs.addGrade("002", 92); gs.addGrade("003", 78); std::cout << "按学号排序:" << std::endl; gs.printAll(); std::cout << "\n按成绩排序:" << std::endl; gs.printByGrade(); return 0; } 案例2:词频统计 #include
#include
#include
#include
#include

int main() {
std::string text = “the quick brown fox jumps over the lazy dog the fox is quick”;
std::map word_count;

// 统计词频
std::istringstream iss(text);
std::string word;
while (iss >> word) {
word_count[word]++;
}

// 输出词频
for (const auto& [word, count] : word_count) {
std::cout << word << ": " << count << std::endl; } // 找出出现次数最多的词 auto max_it = std::max_element(word_count.begin(), word_count.end(), [](const auto& a, const auto& b) { return a.second < b.second; }); std::cout << "\n最频繁的词: " << max_it->first << " (" << max_it->second << "次)" << std::endl; return 0; } 案例3:在线用户管理 #include
#include
#include
#include

class OnlineUserManager {
private:
std::set online_users; // 在线用户
std::map user_sessions; // 用户 -> 会话ID

public:
bool userLogin(const std::string& username, const std::string& session_id) {
if (online_users.find(username) != online_users.end()) {
return false; // 已经在线
}
online_users.insert(username);
user_sessions[username] = session_id;
return true;
}

void userLogout(const std::string& username) {
online_users.erase(username);
user_sessions.erase(username);
}

bool isOnline(const std::string& username) const {
return online_users.find(username) != online_users.end();
}

void printOnlineUsers() const {
std::cout << "在线用户 (" << online_users.size() << "): "; for (const auto& user : online_users) { std::cout << user << " "; } std::cout << std::endl; } }; int main() { OnlineUserManager manager; manager.userLogin("Alice", "session1"); manager.userLogin("Bob", "session2"); manager.userLogin("Charlie", "session3"); manager.printOnlineUsers(); std::cout << "Alice在线: " << (manager.isOnline("Alice") ? "是" : "否") << std::endl; std::cout << "David在线: " << (manager.isOnline("David") ? "是" : "否") << std::endl; manager.userLogout("Bob"); manager.printOnlineUsers(); return 0; } 5. 常见问题总结与解决方案 5.1 内存管理问题 vector重新分配导致迭代器失效 解决方案:在插入/删除后更新迭代器,或使用索引代替 map/set的内存泄漏 解决方案:确保正确释放资源,使用智能指针存储动态分配的对象 不必要的拷贝 解决方案:使用emplace系列函数,移动语义 5.2 性能问题 vector频繁中间插入 解决方案:考虑使用list或deque,或批量插入 map查找性能低 解决方案:考虑unordered_map(如果不需要排序) set元素修改 解决方案:删除后重新插入,或使用mutable成员 5.3 逻辑错误 operator[]的意外创建 解决方案:使用find或at代替 迭代器失效 解决方案:遵循erase返回值更新迭代器 排序规则错误 确保自定义比较器满足严格弱序 5.4 最佳实践总结 预分配内存 :对于vector,使用reserve() 使用emplace :避免不必要的拷贝 选择合适的容器 :根据需求选择vector/map/set 注意迭代器失效 :在修改容器时小心处理 使用const引用 :避免不必要的拷贝 利用C++11+特性 :范围for、auto、结构化绑定等 结论 vector、map和set是C++ STL中最基础也是最强大的容器。理解它们的实现原理、性能特点和适用场景,对于编写高效、可靠的C++代码至关重要。在实际开发中,应该根据具体需求选择合适的容器,并遵循最佳实践来避免常见问题。通过合理使用这些容器,可以大大提高代码的效率和可维护性。