什么是 map?
map 是 C++ 标准库中的一个容器,用于存储键值对(key-value pairs)。它的特点是:
-
键值对:每个元素都是一个键值对,键和值可以是任意类型(比如
int、string等) -
自动排序:
map会根据键的值自动排序(默认是按升序排序) -
唯一键:每个键在
map中是唯一的,不能重复
map 的基本用法
-
定义和初始化:
map<string, int> color_count; // 定义一个 map,键是 string,值是 int -
插入数据:
color_count["pink"] = 2; // 插入键值对 "pink": 2 color_count["red"] = 1; // 插入键值对 "red": 1 color_count["blue"] = 3; // 插入键值对 "blue": 3 -
访问数据:
cout << color_count["pink"]; // 输出 2 -
遍历
map:for (const auto& pair : color_count) { cout << "Color: " << pair.first << ", Count: " << pair.second << endl; } -
检查键是否存在:
if (color_count.find("pink") != color_count.end()) { cout << "Pink exists!" << endl; }
为什么要用 map?
-
快速查找:通过键可以快速查找对应的值
-
自动排序:数据会根据键自动排序
-
唯一键:确保每个键只能出现一次
一道map例题:
测试数据有多组,处理到文件尾(意思是不确定输入数量,要用while (cin >> n))每组数据先输入一个整数n(0<n≤5000)表示接下来的字符串数。接下来输入n行,每行一个表示颜色的字符串(长度不超过20且仅由小写字母构成)
对于每组测试,输出出现次数最多的颜色。若出现并列的情况,则只需输出ASCII码值最小的那种颜色
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
while (cin >> n) { // 处理多组测试数据
map<string, int> color_count; // 定义一个map,用于存储颜色及其出现次数
string color;
// 输入n个颜色,并统计每个颜色的出现次数
for (int i = 0; i < n; i++) {
cin >> color;
color_count[color]++; // 如果颜色已存在,次数加1;否则,插入新颜色并初始化次数为1
}
string max_color; // 用于存储出现次数最多的颜色
int max_count = 0; // 用于存储最大出现次数
// 遍历map,找出出现次数最多的颜色
for (const auto& pair : color_count) {
// 如果当前颜色的出现次数大于最大次数,或者出现次数相等但颜色名称的ASCII码更小
if (pair.second > max_count || (pair.second == max_count && pair.first < max_color)) {
max_count = pair.second; // 更新最大次数
max_color = pair.first; // 更新出现次数最多的颜色
}
}
cout << max_color << endl; // 输出结果
}
return 0;
}
这段代码通过使用 map 来统计每个颜色的出现次数,并通过遍历 map 来找出出现次数最多的颜色
总结
-
map是一个键值对容器,键和值可以是任意类型 -
它自动根据键排序,并且键是唯一的
2146

被折叠的 条评论
为什么被折叠?



