#include <iostream>
#include <map>
#include <string>
int main() {
// 创建一个 map,键为 string 类型,值为 int 类型
std::map<std::string, int> ageMap;
// 插入元素到 map 中
ageMap["Alice"] = 25;
ageMap["Bob"] = 30;
ageMap["Charlie"] = 35;
// 使用 insert 方法插入元素
ageMap.insert(std::make_pair("David", 40));
// 访问 map 中的元素
std::cout << "Alice's age is " << ageMap["Alice"] << std::endl;
// 检查键是否存在
if (ageMap.find("Eve") == ageMap.end()) {
std::cout << "Eve is not in the map." << std::endl;
}
// 遍历 map
for (const auto& pair : ageMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// 删除元素
ageMap.erase("Bob");
// 输出删除后的 map
std::cout << "After erasing Bob:" << std::endl;
for (const auto& pair : ageMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
std::map<std::string, int> 创建一个名为 ageMap 的 map,其中键是字符串类型,值是整数类型。[] 操作符或 insert 方法向 map 中插入元素。[] 操作符可以直接访问 map 中的元素。如果键不存在,会自动插入一个默认值(对于 int 类型,默认值为 0)。find 方法检查某个键是否存在于 map 中。如果找不到该键,find 返回 ageMap.end()。erase 方法删除指定键的元素。希望这段代码和解释能帮助你理解 C++ 中 map 的基本用法。
上一篇:c++ ^
下一篇:c++ 右值引用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站