温馨提示×

c++中怎么用map删除键值对

c++
小亿
180
2024-05-27 17:04:08
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用map提供的erase()函数来删除指定的键值对。具体操作如下:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap;
    
    // 添加键值对
    myMap[1] = "hello";
    myMap[2] = "world";
    
    // 删除键值对
    myMap.erase(1);
    
    // 遍历输出
    for (auto it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
    }
    
    return 0;
}

运行上述代码后,输出结果为:

Key: 2, Value: world

可以看到,通过调用erase()函数删除了键值为1的键值对。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c++ map删除键值对怎么做

0