扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

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

扬州沐宇科技
2024-05-27 17:04:08
c++

在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的键值对。

扫码添加客服微信