为什么需要 STL

写 C++ 程序时,最常遇到的问题不是算法,而是"数据放哪里"。自己手写链表、动态数组既费时又容易出错。STL(Standard Template Library,标准模板库)就是 C++ 自带的工具箱,其中 vector 和 map 是使用频率最高的两个容器。

vector 是可以自动扩容的动态数组,map 是按键(key)快速查找值的键值对容器。把这两个用熟,大多数入门场景就够用了。

vector:会自动扩容的数组

使用 vector 需要包含头文件 <vector>,它是一个模板,尖括号里写元素类型:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> nums;          // 空的 int 数组
    nums.push_back(10);        // 尾部添加元素
    nums.push_back(20);
    nums.push_back(30);

    cout << nums.size() << endl;     // 输出:3
    cout << nums[0] << endl;         // 输出:10(下标访问,不检查越界)
    cout << nums.at(2) << endl;      // 输出:30(越界会抛异常,更安全)
    cout << nums.back() << endl;     // 输出:30
    return 0;
}

创建时也可以直接指定初始值:

vector<int> a = {1, 2, 3};       // 列表初始化
vector<int> b(5, 0);             // 5 个元素,每个都是 0

遍历推荐用范围 for 循环,写起来最清爽:

vector<string> fruits = {"apple", "banana", "cherry"};
for (const string& f : fruits) {
    cout << f << endl;     // 依次输出 apple banana cherry
}

删除元素用 pop_back() 弹出末尾,或 erase() 删除指定位置。在末尾插入、删除都很快,但在中间插入会比较慢,这一点和普通数组一样。

map:按键查找的键值对

map 存的是"键 → 值"的映射,会按键自动排序(默认升序),头文件是 <map>:

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> price;
    price["apple"] = 5;          // 用下标插入
    price["banana"] = 3;
    price.insert({"cherry", 12});

    cout << price["apple"] << endl;         // 输出:5
    cout << price.count("banana") << endl;  // 输出:1(键存在)

    // 遍历时每一项是一个 pair
    for (const auto& p : price) {
        cout << p.first << "=" << p.second << endl;
    }
    // 按 key 升序输出:
    // apple=5
    // banana=3
    // cherry=12
    return 0;
}

注意一个新手常踩的坑:price["pear"] 这种写法在键不存在时会自动插入一个值为 0 的元素。只想查询、不想插入时,用 find() 判断:

if (price.find("pear") != price.end()) {
    cout << "有 pear" << endl;
} else {
    cout << "没有 pear" << endl;   // 会走到这里
}

常用方法速查

vector 常用方法:push_back 尾插、pop_back 尾删、size 长度、empty 是否为空、clear 清空。

map 常用方法:[] 插入或读取、insert 插入、erase 删除键、find 查找、count 统计键个数(结果只会是 0 或 1)。

小结

  • vector 是自动扩容的动态数组,尾插尾删快,下标访问注意越界,追求安全用 at()
  • map 是有序键值对容器,按键升序排列,查找、插入都是 O(log n)
  • map[key] 会隐式插入不存在的键,纯查询场景用 find() 更保险
  • 两者都是模板,把尖括号里的类型换掉,就能存放任何类型的数据

把 vector 和 map 用熟,C++ 的数据结构基本功就打牢了一半,接下来可以继续了解 set、queue、stack 等其他容器。