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.
The Queue<T> generic class in the System. Collections. Generic namespace provides the Contains() method, which can be used to check if an item exists in the queue. This method returns true if the element is present in the queue, and returns false otherwise.
deque class to initialize a deque object, you can directly use the in operator to check if an item is in the deque. Copied! The collections. deque class has atomic append() , implements the popleft() method and supports indexing and membership testing.
→ Following a similar definition, a queue is a container where only the front and back elements can be accessed or operated upon. Queue is a data structure following the FIFO(First In, First Out) principle.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With