i have this iterator loop,
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 function seems to be invalidating the iterator. It pushes new elements inside the NavigationNode and modifies existing members of the NavigationNode.
i have two questions
- Is passing it->second as pointer bad?
- What’s the best way to iterate through this container?
thank you.
edit:
does accessing container’s elements like this
nodes[intpair(x, y)]
inside ConnectNode function would cause this problem?
edit2
yes it does.
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?
The way that you are using is fine. Using
begin()andend()to iterate is pretty standard.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”
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.