Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if an item already exists in STL queue

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.

like image 857
Ari Avatar asked May 11 '12 12:05

Ari


People also ask

How do you find if an element is present in a queue C++?

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.

How do you check if something is in a Deque?

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.

Can you access any element in a queue?

→ 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.


1 Answers

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.

like image 113
Fred Foo Avatar answered Oct 04 '22 04:10

Fred Foo