STL 标准库

C++ 教程 · 第 7 章 · 7 次浏览

STL(Standard Template Library,标准模板库)是 C++ 自带的工具箱:容器(存数据)、迭代器(遍历)、算法(处理)、函数对象。用好 STL,开发效率翻倍。

常用容器

  • vector:动态数组,最常用
  • map:键值对(红黑树,自动排序)
  • unordered_map:哈希键值对,查找更快
  • set:有序不重复集合
  • string:字符串

常用算法

sort 排序、find 查找、max_element 最大值,都在 algorithm 头文件。

迭代器

类似指针,begin() 到 end() 遍历容器。

代码示例

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

int main() {
    // vector
    vector<int> nums = {5, 2, 8, 1, 9};
    sort(nums.begin(), nums.end());          // 排序
    for (int n : nums) cout << n << " ";
    cout << endl;

    // map
    map<string, int> scores;
    scores["语文"] = 90;
    scores["数学"] = 95;
    for (auto &[k, v] : scores) {
        cout << k << ": " << v << endl;
    }

    // 算法
    auto it = max_element(nums.begin(), nums.end());
    cout << "最大值: " << *it << endl;

    return 0;
}