c++

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

小亿
164
2024-05-27 17:04:08
栏目: 编程语言

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

0
看了该问题的人还看了