#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;
// 访问 map 中的元素
cout << "Alice's age: " << ageMap["Alice"] << endl;
// 检查键是否存在
if (ageMap.find("David") == ageMap.end()) {
cout << "David is not in the map." << endl;
}
// 使用迭代器遍历 map
for (auto it = ageMap.begin(); it != ageMap.end(); ++it) {
cout << it->first << "'s age: " << it->second << endl;
}
// 删除一个元素
ageMap.erase("Bob");
// 输出删除后的 map 大小
cout << "Size of map after erasing Bob: " << ageMap.size() << endl;
return 0;
}
创建 map:
map<string, int> ageMap;
:创建了一个名为 ageMap
的 map,键为 string
类型,值为 int
类型。插入元素:
ageMap["Alice"] = 25;
:向 ageMap
中插入键为 "Alice"
,值为 25
的元素。访问元素:
cout << "Alice's age: " << ageMap["Alice"] << endl;
:通过键 "Alice"
访问对应的值,并输出。检查键是否存在:
if (ageMap.find("David") == ageMap.end())
:使用 find
方法检查键 "David"
是否存在。如果不存在,则返回 ageMap.end()
。遍历 map:
for (auto it = ageMap.begin(); it != ageMap.end(); ++it)
遍历整个 map,并输出每个键值对。删除元素:
ageMap.erase("Bob");
:删除键为 "Bob"
的元素。获取 map 大小:
ageMap.size()
:返回 map 中元素的数量。上一篇:c++协程
下一篇:c++绝对值函数怎么用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站