#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// 创建一个 map,键为 int 类型,值为 string 类型
map<int, string> myMap;
// 向 map 中插入元素
myMap[1] = "Apple";
myMap[2] = "Banana";
myMap[3] = "Orange";
// 使用 insert 方法插入元素
myMap.insert(pair<int, string>(4, "Grapes"));
myMap.insert(make_pair(5, "Pineapple"));
// 访问 map 中的元素
cout << "Element with key 1: " << myMap[1] << endl;
cout << "Element with key 3: " << myMap[3] << endl;
// 遍历 map
cout << "All elements in the map:" << endl;
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << "Key: " << it->first << ", Value: " << it->second << endl;
}
// 检查某个键是否存在
if (myMap.find(2) != myMap.end()) {
cout << "Key 2 exists in the map." << endl;
} else {
cout << "Key 2 does not exist in the map." << endl;
}
// 删除某个元素
myMap.erase(3);
// 输出删除后的 map 大小
cout << "Size of the map after erasing element with key 3: " << myMap.size() << endl;
return 0;
}
map<int, string>
创建一个键为 int
类型、值为 string
类型的映射。myMap[key] = value
或者 myMap.insert(pair<int, string>(key, value))
插入元素。myMap[key]
访问指定键的值。for (auto it = myMap.begin(); it != myMap.end(); ++it)
遍历所有元素。myMap.find(key)
查找某个键是否存在。myMap.erase(key)
删除指定键的元素。myMap.size()
获取 map 的大小。这段代码展示了如何使用 C++ 的 std::map
进行基本操作。
上一篇:c++ const_cast
下一篇:c++ 网络库
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站