Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queue with unique entries in c++

Tags:

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.

like image 364
Adhithya Avatar asked Jul 30 '12 07:07

Adhithya


People also ask

Can queue have duplicates?

The first and most important difference is one is Set and the other is Queue, which means one doesn't allow duplicate while the other is FIFO data structure without any restriction on duplication.

Does priority queue allow duplicate values?

Answer: Yes. Priority Queue allows duplicate values.

What is enqueue and dequeue in C?

Enqueue- adding an element in the queue if there is space in the queue. Dequeue- Removing elements from a queue if there are any elements in the queue. Front- get the first item from the queue. Rear- get the last item from the queue. isEmpty/isFull- checks if the queue is empty or full.


1 Answers

How about an auxiliary data structure to track uniqueness:

std::queue<Foo> q;
std::set<std::reference_wrapper<Foo>> s;

// to add:

void add(Foo const & x)
{
    if (s.find(x) == s.end())
    {
        q.push_back(x);
        s.insert(std::ref(q.back()));  // or "s.emplace(q.back());"
    }
}

Or, alternatively, reverse the roles of the queue and the set:

std::set<Foo> s;
std::queue<std::reference_wrapper<Foo>> q;

void add(Foo const & x)
{
    auto p = s.insert(x);       // std::pair<std::set<Foo>::iterator, bool>
    if (s.second)
    {
        q.push_back(std::ref(*s.first));  // or "q.emplace_back(*s.first);"
    }
}
like image 135
Kerrek SB Avatar answered Sep 28 '22 22:09

Kerrek SB