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

map c++

作者:至尊巅峰   发布日期:2025-12-20   浏览:89

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

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

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

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

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

    // 遍历 map
    for (const auto& pair : ageMap) {
        std::cout << pair.first << " is " << pair.second << " years old." << std::endl;
    }

    return 0;
}

解释说明:

  1. 创建 mapstd::map<std::string, int> ageMap; 创建了一个 map,其中键是 string 类型,值是 int 类型。
  2. 插入元素:使用 ageMap["Alice"] = 25; 等语句将键值对插入到 map 中。
  3. 访问元素:通过 ageMap["Alice"] 访问 map 中的值。
  4. 检查键是否存在:使用 find 方法检查某个键是否存在于 map 中。如果不存在,则返回 map.end()
  5. 遍历 map:使用范围 for 循环遍历 map 中的所有键值对,并输出它们。

希望这段代码和解释对你有帮助!

上一篇:c++ foreach

下一篇:c++向下取整

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

c++ random函数用法

队列c++

c++freopen怎么用

c++virtual

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

Laravel 中文站