第二节 · 一一对应 · 关联容器
容器
说明
特点
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
map<string, int> scores;
// 插入元素
scores["Alice"] = 95;
scores["Bob"] = 87;
scores.insert({"Carol", 92});
scores.insert(make_pair("David", 78));
// 访问元素
cout << scores["Alice"] << endl; // 95
cout << scores.at("Bob") << endl; // 87
// 注意:[] 访问不存在的键会创建该键!
cout << scores["Unknown"] << endl; // 0(新创建的)
// 安全地检查键是否存在
if (scores.find("Eve") != scores.end())
cout << "找到了" << endl;
else
cout << "没找到" << endl;
// 或使用 count
if (scores.count("Alice") > 0)
cout << "Alice 存在" << endl;
// 遍历(按键排序)
for (const auto& pair : scores)
{
cout << pair.first << ": " << pair.second << endl;
}
// C++17 结构化绑定
for (const auto& [name, score] : scores)
{
cout << name << ": " << score << endl;
}
return 0;
}习题
Last updated