C++ 从入门到精通C++ 从入门到精通
首页
基础教程
进阶教程
实战项目
编程指南
首页
基础教程
进阶教程
实战项目
编程指南
  • 💪 进阶基础

    • 📚 C++ 进阶教程
    • 第8章 - 指针基础
    • 第9章 - 引用和动态内存
    • 第10章 - 结构体和枚举
    • 第11章 - 文件操作
    • 第12章 - 预处理器和命名空间
  • 🎯 面向对象编程

    • 第13章 - 类和对象基础
    • 第14章 - 构造函数和析构函数
    • 第15章 - 封装、继承、多态
    • 第16章 - 运算符重载
    • 第17章 - 模板基础
    • 第18章 - 异常处理
  • 📦 STL 标准模板库

    • 第19章 - Vector 和 String
    • 第20章 - 容器类
    • 第21章 - Map 和 Set
    • 第22章 - 算法和迭代器

第21章 - Map 和 Set

嗨,朋友!我是长安。

这一章学习两个非常实用的关联容器:map(映射)和set(集合)。

🗺️ Map - 键值对容器

Map存储键值对,每个键唯一,可以快速通过键查找值。

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

int main() {
    // 创建map
    map<string, int> ages;
    
    // 添加元素
    ages["张三"] = 20;
    ages["李四"] = 25;
    ages["王五"] = 22;
    ages.insert({"赵六", 28});
    
    // 访问元素
    cout << "张三的年龄:" << ages["张三"] << endl;
    
    // 遍历
    cout << "\n所有人的年龄:" << endl;
    for (auto& pair : ages) {
        cout << pair.first << ": " << pair.second << " 岁" << endl;
    }
    
    // 查找
    if (ages.find("李四") != ages.end()) {
        cout << "\n找到李四" << endl;
    }
    
    // 删除
    ages.erase("王五");
    
    // 大小
    cout << "共有 " << ages.size() << " 个人" << endl;
    
    return 0;
}

输出:

张三的年龄:20

所有人的年龄:
李四: 25 岁
张三: 20 岁
赵六: 28 岁

找到李四
共有 3 个人

📊 Map实战:单词统计

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

int main() {
    string text = "hello world hello cpp world hello";
    map<string, int> wordCount;
    
    // 分词并统计
    istringstream iss(text);
    string word;
    while (iss >> word) {
        wordCount[word]++;
    }
    
    // 输出结果
    cout << "单词统计:" << endl;
    for (auto& pair : wordCount) {
        cout << pair.first << ": " << pair.second << " 次" << endl;
    }
    
    return 0;
}

输出:

单词统计:
cpp: 1 次
hello: 3 次
world: 2 次

🎯 Set - 集合容器

Set存储唯一元素,自动排序,不允许重复。

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

int main() {
    set<int> numbers;
    
    // 添加元素
    numbers.insert(30);
    numbers.insert(10);
    numbers.insert(50);
    numbers.insert(20);
    numbers.insert(10);  // 重复,不会添加
    
    // 自动排序,去重
    cout << "集合内容:";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // 查找
    if (numbers.find(20) != numbers.end()) {
        cout << "找到 20" << endl;
    }
    
    // 删除
    numbers.erase(30);
    
    // 大小
    cout << "大小:" << numbers.size() << endl;
    
    return 0;
}

输出:

集合内容:10 20 30 50
找到 20
大小:3

🌟 实战案例:学生成绩管理

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

class ScoreManager {
private:
    map<string, double> scores;
    
public:
    void addScore(string name, double score) {
        scores[name] = score;
        cout << "添加/更新:" << name << " - " << score << endl;
    }
    
    void removeStudent(string name) {
        if (scores.erase(name)) {
            cout << "删除:" << name << endl;
        } else {
            cout << "未找到:" << name << endl;
        }
    }
    
    void queryScore(string name) {
        auto it = scores.find(name);
        if (it != scores.end()) {
            cout << name << " 的成绩:" << it->second << endl;
        } else {
            cout << "未找到 " << name << endl;
        }
    }
    
    void displayAll() {
        cout << "\n===== 成绩列表 =====" << endl;
        for (auto& pair : scores) {
            cout << pair.first << ": " << pair.second << endl;
        }
    }
    
    double getAverage() {
        if (scores.empty()) return 0;
        
        double sum = 0;
        for (auto& pair : scores) {
            sum += pair.second;
        }
        return sum / scores.size();
    }
};

int main() {
    ScoreManager mgr;
    
    mgr.addScore("张三", 95.5);
    mgr.addScore("李四", 88.0);
    mgr.addScore("王五", 92.0);
    
    mgr.displayAll();
    
    mgr.queryScore("李四");
    
    cout << "\n平均分:" << mgr.getAverage() << endl;
    
    mgr.removeStudent("王五");
    mgr.displayAll();
    
    return 0;
}

🔄 multimap 和 multiset

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

int main() {
    // multimap - 允许重复键
    multimap<string, int> scores;
    scores.insert({"张三", 95});
    scores.insert({"张三", 88});  // 同一个人多次成绩
    scores.insert({"李四", 92});
    
    cout << "multimap内容:" << endl;
    for (auto& p : scores) {
        cout << p.first << ": " << p.second << endl;
    }
    
    // multiset - 允许重复元素
    multiset<int> nums;
    nums.insert(10);
    nums.insert(20);
    nums.insert(10);  // 可以重复
    
    cout << "\nmultiset内容:";
    for (int n : nums) {
        cout << n << " ";
    }
    cout << endl;
    
    return 0;
}

🎯 小结

容器特点用途
map键值对,键唯一,自动排序字典、映射关系
multimap键值对,键可重复一对多关系
set元素唯一,自动排序去重、集合运算
multiset元素可重复,自动排序需要排序的多重集合

常用操作:

  • insert() - 插入
  • erase() - 删除
  • find() - 查找
  • size() - 大小
  • clear() - 清空

➡️ 第22章 - 算法和迭代器

最近更新: 2025/12/26 17:25
Contributors: 王长安
Prev
第20章 - 容器类
Next
第22章 - 算法和迭代器