#include <iostream>
#include <map>
#include <string>
int main() {
// 创建一个 map,键为 int 类型,值为 string 类型
std::map<int, std::string> myMap;
// 插入元素到 map 中
myMap[1] = "Apple";
myMap[2] = "Banana";
myMap[3] = "Orange";
// 使用 insert 方法插入元素
myMap.insert(std::make_pair(4, "Grape"));
// 访问 map 中的元素
std::cout << "Element with key 2: " << myMap[2] << std::endl;
// 遍历 map 并打印所有元素
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
// 检查某个键是否存在
if (myMap.find(3) != myMap.end()) {
std::cout << "Key 3 exists in the map." << std::endl;
} else {
std::cout << "Key 3 does not exist in the map." << std::endl;
}
// 删除某个键值对
myMap.erase(1);
// 打印删除后的 map 大小
std::cout << "Map size after erasing key 1: " << myMap.size() << std::endl;
return 0;
}
std::map<int, std::string> 创建了一个键为整数类型、值为字符串类型的 map。[] 操作符或 insert() 方法插入元素。[] 操作符根据键访问对应的值。find() 方法检查某个键是否存在于 map 中。erase() 方法删除指定键的键值对。size() 方法获取 map 中元素的数量。上一篇:c++ 20
下一篇:c++ 读取文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站