I need to implement a queue containing unique entries(no duplicates) in C or C++. I am thinking of maintaining a reference of elements already available in queue but that seems very inefficient.
Kindly let me know your suggestions to tackle this.
I need to implement a queue containing unique entries(no duplicates) in C or C++. I am thinking of maintaining a reference of elements already available in queue but that seems very inefficient.
Kindly let me know your suggestions to tackle this.
queuing:
dequeueing:
There is one very important point you've not mentioned in your question, and that is whether your queue of items is sorted or have some kind of ordering (called a Priority queue), or unsorted (called a plain FIFO). The solution you choose will depend only on the answer to this question.
If your queue is unsorted, then maintaining an extra data structure in addition to your queue will be more efficient. Using a second structure which is ordered in some way to maintain the contents of your queue will allow you check if an item already exists in your queue or not much quicker that scanning the queue itself. Adding to the end of an unsorted queue takes constant time and can be done very efficiently.
If your queue must be sorted, then placing the item into the queue requires you to know the item's position in the queue, which requires the queue to be scanned anyway. Once you know an item's position, you know if the item is a duplicate because if it's a duplicate then an item will already exist at that position in the queue. In this case, all work can be performed optimally on the queue itself and maintaining any secondary data structure is unnecessary.
The choice of data structures is up to you. However, for (1) the secondary data structure should not be any kind of list or array, otherwise it will be no more efficient to scan your secondary index as to scan the original queue itself.
How about an auxiliary data structure to track uniqueness:
Or, alternatively, reverse the roles of the queue and the set:
std::queue
is a container adaptor and uses relatively few members of the underlyingContainer
. You can easily implement a custom container that contains both: anunordered_map
ofreference_wrapper<T>
and adeque<T>
. It needs at least membersfront
andpush_back
. Check inside thathash_map
whenpush_back
of your container is called and reject accordingly (possibly throw). To give the complete example:EDIT: You will want to make
my_container
a proper model of container (maybe also allocators), but this is another full question. Thanks to Christian Rau for pointing out bugs.