地图删除地图的难度

时间:2013-03-31 02:46:24

标签: c++

如何删除地图地图内部地图的第一个元素?

我尝试过像

这样的事情
my_map[here].erase(my_map[here].begin()) 

但是我得到了意想不到的结果。任何建议或资源都会很棒。

1 个答案:

答案 0 :(得分:1)

my_map [here]确实存在吗?

你可能想找到它,即

if((auto it = my_map.find(here)) != my_map.end()) {
  it->erase(it->begin());

}

如果my_map [here]在您尝试访问它时不存在,那么将在那里创建一个新元素:

http://www.cplusplus.com/reference/map/map/operator%5B%5D/

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

为防止这种情况发生,您可以使用我上面指出的find功能。 find使用指定的密钥搜索元素。如果找到了某些内容,它会将迭代器返回给该元素。否则,它将返回my_map.end(),它不是最后一个元素,而是一个表示结构结束的特殊迭代器。