C++的std::map怎么使用
使用std::map需要包含头文件
下面是std::map的基本用法示例:
#include <iostream>#include <map>int main() {// 创建一个std::map对象std::map<int, std::string> students;// 插入键值对students.insert(std::make_pair(1, "Alice"));students.insert(std::make_pair(2, "Bob"));students.insert(std::make_pair(3, "Charlie"));// 通过键访问值std::cout << "Student with key 1: " << students[1] << std::endl;// 修改值students[2] = "Ben";// 遍历std::mapstd::cout << "All students:" << std::endl;for (const auto& student : students) {std::cout << "Key: " << student.first << ", Value: " << student.second << std::endl;}// 检查键是否存在if (students.count(3) > 0) {std::cout << "Student with key 3 exists" << std::endl;}// 删除键值对students.erase(2);return 0;}
这个示例演示了如何创建std::map对象、插入键值对、访问和修改值、遍历std::map以及删除键值对。注意,通过[]操作符访问不存在的键会插入一个新的键值对。
上述示例的输出应为:
Student with key 1: AliceAll students:Key: 1, Value: AliceKey: 2, Value: BenKey: 3, Value: CharlieStudent with key 3 exists
下一篇:Nagios的安装和基本配置
输入法切换键是哪个键?输入法切
冬月是哪一个月?冬月是什么意思
个人所得税退税金额怎么算出来的
输入法全角和半角有什么区别?输
a4纸尺寸是多少厘米?a4纸的由来
个人所得税扣除标准?个人所得税
输入法哪个好用?输入法介绍
卡拉OK是哪个国家发明的?卡拉OK
mikutools原神网页版入口链接?m
关机特别慢什么原因?电脑和手机