C++中的Map容器提供了两种方法来删除元素:
std::map<int, std::string> map;
map[1] = "apple";
map[2] = "banana";
map.erase(1); // 删除键为1的元素
// 遍历Map容器并输出剩余元素
for(auto it = map.begin(); it != map.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
std::map<int, std::string> map;
map[1] = "apple";
map[2] = "banana";
auto it = map.find(1);
if(it != map.end()) {
map.erase(it); // 删除键为1的元素
}
// 遍历Map容器并输出剩余元素
for(auto it = map.begin(); it != map.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
无论使用哪种方法,都可以方便地删除Map容器中的元素。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:C++ Map容器如何保证顺序