#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;
// 访问 map 中的元素
std::cout << "Alice's age is " << ageMap["Alice"] << std::endl;
// 检查键是否存在
if (ageMap.find("David") == ageMap.end()) {
std::cout << "David is not in the map." << std::endl;
}
// 遍历 map
for (const auto& pair : ageMap) {
std::cout << pair.first << " is " << pair.second << " years old." << std::endl;
}
return 0;
}
std::map<std::string, int> ageMap; 创建了一个 map,其中键是 string 类型,值是 int 类型。ageMap["Alice"] = 25; 等语句将键值对插入到 map 中。ageMap["Alice"] 访问 map 中的值。find 方法检查某个键是否存在于 map 中。如果不存在,则返回 map.end()。for 循环遍历 map 中的所有键值对,并输出它们。希望这段代码和解释对你有帮助!
上一篇:c++ foreach
下一篇:c++向下取整
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站