21xrx.com
2024-06-03 03:52:17 Monday
登录
文章检索 我的文章 写文章
如何在C++中删除指定的Map键(key)?
2023-06-30 10:50:21 深夜i     --     --
C++ Map 删除 键值对

在C++中,Map是一种常用的关联式容器,它可以由键与值构成的映射关系。如果我们想要从Map中删除特定的键值对,该怎么做呢?本文将介绍如何在C++中删除指定的Map键。

在C++中,Map是通过使用std :: map类来实现的。为了删除指定键值对,我们需要使用std :: map类的erase()函数。 该函数可以接受指定键所对应的迭代器作为参数。

例如,我们可以使用以下代码将Map中的指定键值对删除:


#include <iostream>

#include <map>

using namespace std;

int main() {

  std::map<int, string> m{ "apple","banana","orange","pear" };

  // 打印Map内容

  cout << "Map elements before deletion : " << endl;

  for (auto it = m.begin(); it != m.end(); it++)

    cout << it->first << " " << it->second << endl;

  

  // 删除Map中的指定元素

  m.erase(2);

  // 再次打印Map内容

  cout << "Map elements after deletion : " << endl;

  for (auto it = m.begin(); it != m.end(); it++)

    cout << it->first << " " << it->second << endl;

  

  return 0;

}

在上面的代码中,我们通过使用erase()函数从Map中删除了键为2的元素。通过运行程序,我们可以看到Map中只留下了键为1、3和4的元素。

总的来说,在C++中删除Map键非常简单。只需要使用erase()函数并将要删除的键作为参数传递即可。不过需要注意的是,在尝试删除Map中不存在的键时,应该谨慎处理,以避免程序出错。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复