首页主机资讯C++的std::map怎么使用

C++的std::map怎么使用

时间2023-12-21 17:33:22发布访客分类主机资讯浏览387
导读:使用std::map需要包含头文件。std::map是一个关联容器,用于存储键值对,其中的键是唯一的。 下面是std::map的基本用法示例: #include <iostream> #include <map>...

使用std::map需要包含头文件。std::map是一个关联容器,用于存储键值对,其中的键是唯一的。

下面是std::map的基本用法示例:

#include iostream>
    
#include map>


int main() {
    
    // 创建一个std::map对象
    std::mapint, 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::map
    std::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: Alice
All students:
Key: 1, Value: Alice
Key: 2, Value: Ben
Key: 3, Value: Charlie
Student with key 3 exists

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: C++的std::map怎么使用
本文地址: https://pptw.com/jishu/578866.html
eslint插件配置的步骤是什么 java怎么获取hashmap的值

游客 回复需填写必要信息