问题解答之C++MAP

C++中的MAP是一种关联容器,它存储了一对一的键值对。下面是一个使用C++中的MAP的示例代码:

#include <iostream>
#include <map>
 
int main() {
    // 创建一个空的map对象
    std::map<std::string, int> map;
 
    // 向map中插入键值对
    map["apple"] = 10;
    map["banana"] = 20;
    map["orange"] = 15;
 
    // 使用迭代器遍历map中的键值对
    std::map<std::string, int>::iterator it;
    for (it = map.begin(); it != map.end(); ++it) {
        std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
    }
 
    // 根据键查找对应的值
    std::string key = "banana";
    if (map.find(key) != map.end()) {
        int value = map[key];
        std::cout << "Value of key " << key << ": " << value << std::endl;
    } else {
        std::cout << "Key " << key << " not found in the map." << std::endl;
    }
 
    return 0;
}

这段代码展示了如何创建一个空的map对象,插入键值对,遍历map中的键值对,并根据给定的键查找对应的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值