#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// 创建一个 map,键为 string 类型,值为 int 类型
map<string, int> ageMap;
// 插入元素到 map 中
ageMap["Alice"] = 25;
ageMap["Bob"] = 30;
ageMap["Charlie"] = 35;
// 查找元素
if (ageMap.find("Alice") != ageMap.end()) {
cout << "Alice 的年龄是: " << ageMap["Alice"] << endl;
}
// 遍历 map
for (auto& pair : ageMap) {
cout << pair.first << " 的年龄是: " << pair.second << endl;
}
// 删除元素
ageMap.erase("Bob");
// 检查元素是否存在
if (ageMap.count("Bob") == 0) {
cout << "Bob 不在 map 中" << endl;
}
// 获取 map 的大小
cout << "map 中有 " << ageMap.size() << " 个元素" << endl;
return 0;
}
std::map 模板类创建一个映射表,键为 string 类型,值为 int 类型。[] 操作符将键值对插入到 map 中。find 方法查找键是否存在于 map 中,并通过 end() 判断查找结果。erase 方法根据键删除指定的元素。count 方法检查某个键是否存在于 map 中。size 方法获取 map 中元素的数量。上一篇:c++ string 长度
下一篇:v c++
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站