Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++map的使用

作者:古枕清风   发布日期:2025-06-16   浏览:20

#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;
}

解释说明:

  1. 创建 map:使用 map<int, string> 创建一个键为 int 类型、值为 string 类型的映射。
  2. 插入元素:可以通过 myMap[key] = value 或者 myMap.insert(pair<int, string>(key, value)) 插入元素。
  3. 访问元素:通过 myMap[key] 访问指定键的值。
  4. 遍历 map:使用迭代器 for (auto it = myMap.begin(); it != myMap.end(); ++it) 遍历所有元素。
  5. 查找元素:使用 myMap.find(key) 查找某个键是否存在。
  6. 删除元素:使用 myMap.erase(key) 删除指定键的元素。
  7. 获取大小:使用 myMap.size() 获取 map 的大小。

这段代码展示了如何使用 C++ 的 std::map 进行基本操作。

上一篇:c++ const_cast

下一篇:c++ 网络库

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站