以下是一篇面向初学者的C++ STL容器入门教程,重点介绍三种最常用的容器及其基本操作:


C++ STL容器入门指南

STL(Standard Template Library)是C++标准库的核心组成部分,提供了高效的容器(如数组、链表、映射等)和算法。本文将通过代码示例手把手教你使用以下容器:

  1. vector(动态数组)
  2. map(键值对集合)
  3. set(唯一元素集合)

1. vector:动态数组

vector类似于普通数组,但支持自动扩容。

基本操作:

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

int main() {
    // 初始化
    vector<int> nums = {10, 20, 30};

    // 尾部添加元素
    nums.push_back(40);  // {10, 20, 30, 40}

    // 访问元素(支持索引)
    cout << nums[0] << endl;  // 输出:10

    // 遍历
    for (int i = 0; i < nums.size(); i++) {
        cout << nums[i] << " ";  // 输出:10 20 30 40
    }
    return 0;
}


2. map:键值对集合

map以键(key)和值(value)的形式存储数据,键具有唯一性。

基本操作:

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

int main() {
    // 初始化
    map<string, int> scores = {{"Alice", 90}, {"Bob", 85}};

    // 插入新键值对
    scores["Charlie"] = 88;  // {"Alice":90, "Bob":85, "Charlie":88}

    // 查找元素
    if (scores.find("Bob") != scores.end()) {
        cout << "Bob的分数:" << scores["Bob"] << endl;  // 输出:85
    }

    // 遍历
    for (auto& pair : scores) {
        cout << pair.first << ": " << pair.second << endl;
    }
    return 0;
}


3. set:唯一元素集合

set自动去重,并默认按升序排列元素。

基本操作:

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

int main() {
    // 初始化
    set<int> uniqueNums = {3, 1, 2};

    // 插入元素(自动去重)
    uniqueNums.insert(2);  // 集合仍为 {1, 2, 3}

    // 检查元素是否存在
    if (uniqueNums.count(3) > 0) {
        cout << "3存在!" << endl;
    }

    // 遍历(有序输出)
    for (int num : uniqueNums) {
        cout << num << " ";  // 输出:1 2 3
    }
    return 0;
}


核心注意事项

  1. 越界访问:vector的[]操作符不检查边界,建议用.at(i)(会抛异常)。
  2. 查找效率:map和set基于红黑树实现,查找时间复杂度为 $O(\log n)$。
  3. 迭代器失效:在vector中插入元素可能导致原有迭代器失效。

练习建议:
尝试用vector存储学生姓名,用map关联姓名与分数,并用set记录不及格学生名单。

更多推荐