Unordered_map迭代器失效 [英] Unordered_map iterator invalidation

查看:1387
本文介绍了Unordered_map迭代器失效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个迭代器循环,

typedef  boost::unordered_map<std::pair<int, int>, NavigationNode> NodesMap;
NodesMap nodes;
for (NodesMap::iterator it= nodes.begin(); it != nodes.end() ; ++it)
{

  if(it->second.type == NavigationNodeType_Walkable)
  {
    ConnectNode(&it->second);
  }

}

ConnectNode函数似乎无效迭代器。它在NavigationNode中推送新元素并修改NavigationNode的现有成员。

ConnectNode function seems to be invalidating the iterator. It pushes new elements inside the NavigationNode and modifies existing members of the NavigationNode.

我有两个问题


  • 传递它 - >秒指针坏了吗?

  • 迭代这个容器的最佳方法是什么?

谢谢。

编辑

访问这样的容器元素

   nodes[intpair(x, y)]

会导致此问题吗?

edit2
是的。

为什么会这样?我将如何解决它?

Why is that? and How would i get around it?

推荐答案


  • 传递它 - >秒为指针不好?

    • Is passing it->second as pointer bad?

      这取决于指针本身的功能。孤立地看,传递指针没有任何内在错误。

      It depends on what the function that takes the pointer itself does. Taken in isolation, there is nothing inherently wrong with passing a pointer.

      迭代这个容器的最佳方法是什么?

      What's the best way to iterate through this container?

      您使用的方式很好。使用 begin() end()进行迭代非常标准。

      The way that you are using is fine. Using begin() and end() to iterate is pretty standard.

      所以我认为问题必须是 ConnectNode ,而且很可能你没有迭代器失效问题,但还有其它问题。

      So I think the problem must be with the ConnectNode, and it is likely that you do not have an iterator invalidation problem, but something else.

      确实访问了像这样的容器元素

      "does accessing container's elements like this"

      nodes[intpair(x, y)]
      

      这将添加一个新条目到地图是一个键 intpair(x,y)不存在,所以是的,这可能搞乱迭代。您可以通过在使用 [] 运算符访问之前检查该键是否存在该元素来避免这种情况。

      This will add a new entry to the map is one with key intpair(x,y) doesn't exist, so yes, this could mess up the iteration. You can avoid this by checking if the element exists for that key before accessing with the [] operator.

      这篇关于Unordered_map迭代器失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆