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

c++ map的用法

作者:夜雨行空   发布日期:2025-07-21   浏览:99

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main() {
    // 创建一个 map,键为 string 类型,值为 int 类型
    map<string, int> ageMap;

    // 向 map 中插入元素
    ageMap["Alice"] = 25;
    ageMap["Bob"] = 30;
    ageMap["Charlie"] = 35;

    // 访问 map 中的元素
    cout << "Alice's age: " << ageMap["Alice"] << endl;

    // 检查键是否存在
    if (ageMap.find("David") == ageMap.end()) {
        cout << "David is not in the map." << endl;
    }

    // 使用迭代器遍历 map
    for (auto it = ageMap.begin(); it != ageMap.end(); ++it) {
        cout << it->first << "'s age: " << it->second << endl;
    }

    // 删除一个元素
    ageMap.erase("Bob");

    // 输出删除后的 map 大小
    cout << "Size of map after erasing Bob: " << ageMap.size() << endl;

    return 0;
}

解释说明:

  1. 创建 map

    • map<string, int> ageMap;:创建了一个名为 ageMap 的 map,键为 string 类型,值为 int 类型。
  2. 插入元素

    • ageMap["Alice"] = 25;:向 ageMap 中插入键为 "Alice",值为 25 的元素。
  3. 访问元素

    • cout << "Alice's age: " << ageMap["Alice"] << endl;:通过键 "Alice" 访问对应的值,并输出。
  4. 检查键是否存在

    • if (ageMap.find("David") == ageMap.end()):使用 find 方法检查键 "David" 是否存在。如果不存在,则返回 ageMap.end()
  5. 遍历 map

    • 使用迭代器 for (auto it = ageMap.begin(); it != ageMap.end(); ++it) 遍历整个 map,并输出每个键值对。
  6. 删除元素

    • ageMap.erase("Bob");:删除键为 "Bob" 的元素。
  7. 获取 map 大小

    • ageMap.size():返回 map 中元素的数量。

上一篇:c++协程

下一篇:c++绝对值函数怎么用

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

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

Laravel 中文站