租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

c++中如何用map删除键值对,c++ map 释放内存

发布时间:2024-05-27 17:04:08

c++中如何用map删除键值对

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