Find if an item already exists in STL queue

无人久伴 提交于 2019-12-23 12:07:56

问题


I am using an STL queue to implement a BFS (breadth first search) on a graph. I need to push a node in the queue if that node already doesn't exist in the queue. However, STL queue does not allow iteration through its elements and hence I cannot use the STL find function.

I could use a flag for each node to mark them when they are visited and push them only when the flag is false, however, I need to run BFS multiple times and after each time I will have to reset all the flags, so I ended up using a counter instead of a flag, but I still would like to know if there is a standard way of finding an item in a queue.


回答1:


I assume you're implementing the concept of a "closed set" in your BFS? The standard way of doing that is to simply maintain a separate std::set or std::unordered_set of elements already encountered. That way, you get O(lg n) or O(1) lookup, while iterating through a queue, if it were supported, would take O(n) time.



来源:https://stackoverflow.com/questions/10550962/find-if-an-item-already-exists-in-stl-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!