Priority queue in C++ is out of order after pop() - c++

I created a priority queue of Events, which is sorted by Event.time. I inserted 5 events and it worked very well (they are sorted in order of Event.time). However, after I pop(), the remaining queue are out of order (not sorted anymore). Can someone help me explain why ? Thanks a lot.
struct Event
{
string name;
int time;
int pid;
};
class CompareEvent
{
public:
bool operator()(Event& event1, Event& event2)
{
if (event1.time > event2.time)
return true;
return false;
}
};
main class
priority_queue<Event, vector<Event>, CompareEvent> eventList;
Event newEvent;
newEvent.name = eventName;
newEvent.time = time;
newEvent.pid = pid;
eventList.push(newEvent);
eventList.pop(); // the remaining items are not in order anymore
Updated solution: I debugged the program and I looked at the eventList value in the debug windows. The values are not sorted. However, it always return the lowest value when top(). The values are not sorted internally. Thanks for making me realize this.

Priority queue is not required to be sorted. Only requirement is the heap property - if you call pop() or top(), it has to return the top element (the lowest one given the sorting function).
If you need a container that keeps elements sorted, use std::set or std::map.

If you need sorted events at all time, you have to sort or use a sorting container like set or map. The priority_queue only guarantees that pop() returns one of the lowest element (the top) in it.

Related

Deleting element in priority queue other than top element in C++

Is there any inbuilt function for deleting a given element (other than top element) in priority queue class of C++ STL? If not how to delete it in O(log n)?Should i implement the heap data structure from scratch for this 'delete' functionality?
Is there any inbuilt function for deleting a given element (other than top element) in priority queue class of C++ STL?
No.
If not how to delete it in O(log n)?
By using another container. std::set is the simplest compromise. A custom heap implementation may be more optimal.
There is no inbuilt function for deleting a given element(other than top element) in priority queue.
I would recommend you to use std::set which performs the operations in O(logN) by implementing binary tree. But in case you need more better time complexity use std::unordered_set which performs operations in O(1) time and uses hashing.
So my advice will be that use std::set or std::unordered_set & don't restrict yourself to priority queue only.
As suggested by this solution, you can do something like this:
template<typename T>
class custom_priority_queue : public std::priority_queue<T, std::vector<T>>
{
public:
template< typename UnaryPredicate >
T pop_match_or_top(UnaryPredicate p) {
auto it = std::find_if(this->c.begin(), this->c.end(), p);
if (it != this->c.end()) {
T value = std::move(*it);
this->c.erase(it);
std::make_heap(this->c.begin(), this->c.end(), this->comp);
return value;
}
else {
T value = this->top();
this->pop();
return value;
}
}
};
This is specially useful when you need to take elements that are close to the top but are not exactly the top.

C++ N-last added items container

I try to find optimal data structure for next simple task: class which keeps N last added item values in built-in container. If object obtain N+1 item it should be added at the end of the container and first item should be removed from it. It like a simple queue, but class should have a method GetAverage, and other methods which must have access to every item. Unfortunately, std::queue doesn't have methods begin and end for this purpose.
It's a part of simple class interface:
class StatItem final
{
static int ITEMS_LIMIT;
public:
StatItem() = default;
~StatItem() = default;
void Reset();
void Insert(int val);
int GetAverage() const;
private:
std::queue<int> _items;
};
And part of desired implementation:
void StatItem::Reset()
{
std::queue<int> empty;
std::swap(_items, empty);
}
void StatItem::Insert(int val)
{
_items.push(val);
if (_items.size() == ITEMS_LIMIT)
{
_items.pop();
}
}
int StatItem::GetAverage() const
{
const size_t itemCount{ _items.size() };
if (itemCount == 0) {
return 0;
}
const int sum = std::accumulate(_items.begin(), _items.end(), 0); // Error. std::queue doesn't have this methods
return sum / itemCount;
}
Any ideas?
I'm not sure about std::deque. Does it work effective and should I use it for this task or something different?
P.S.: ITEMS_LIMIT in my case about 100-500 items
The data structure you're looking for is a circular buffer. There is an implementation in the Boost library, however in this situation since it doesn't seem you need to remove items you can easily implement one using a std::vector or std::array.
You will need to keep track of the number of elements in the vector so far so that you can average correctly until you reach the element limit, and also the current insertion index which should just wrap when you reach that limit.
Using an array or vector will allow you to benefit from having a fixed element limit, as the elements will be stored in a single block of memory (good for fast memory access), and with both data structures you can make space for all elements you need on construction.
If you choose to use a std::vector, make sure to use the 'fill' constructor (http://www.cplusplus.com/reference/vector/vector/vector/), which will allow you to create the right number of elements from the beginning and avoid any extra allocations.

Priority Queue implementation - logical error in C++?

I'm trying to compare hsld (integer) in a structure called AdjList.
This is the function to be used for comparisons when entering pointers to the priority queue.
struct CompareHSLD
{
bool operator()(AdjList* const p1, AdjList* const p2)
{
return p1->hsld < p2->hsld;
}
};
This is the priority queue declaration.
priority_queue<AdjList*, vector<AdjList*>, CompareHSLD> PriQueueAdj;
Unable to figure out what the error is in this implementation. There is no syntax error but the priority queue doesn't seem to be sorted. It pops out the wrong elements.
Should it be p1->hsld > p2.hsld if I want to pop the lowest value elements first?

Is it possible to modify the next element (oldest element) in a c++ queue?

Consider a queue of type packet
queue < packet > buffer;
where
struct packet {
int src_id;
int dst_id;
int inter_dst_id;
bool phase;
};
Now, consider this:
if (buffer[i].Front().inter_dst_id == local_id && buffer[i].Front().phase == true)
buffer[i].Front().phase = false;
But I can't write to 'phase' in the above case. Is it possible by any means? Thanks in advance.
Is it possible to modify the next element (oldest element) in a c++ queue?
Yes, like this:
buffer.front().phase = false;
See more on std::queue here.
#juanchopanza : I could not make the above thing work. Seems like you can not modify the front element of a queue. Instead, I used deque.
deque <packet> buffer;
then, I copied buffer[i].front to a temp variable. I changed the phase in the temp variable. Removed the buffer[i].front using pop_front(). Finally, pushed the temp variable with modified phase using push_front().
I am new to stl and hence took some time. I am not sure if this is the best way to do this, but it works for me.

implement a queue

I have the following queue class (taken from wordpress):
#include<iostream.h>
class Queue
{
private:
int data;
Queue*next;
public:
void Enque(int);
int Deque();
}*head,*tail;
void Queue::enque(int data)
{
Queue *temp;
temp=new Queue;
temp->data=data;
temp->next=NULL;
if(heads==NULL)
heads=temp;
else
tail->next=temp;
tail=temp;
}
int Queue::deque()
{
Queue* temp;//
temp=heads;
heads=heads->next;
return temp->data;
}
I'm trying to figure out why the compiler tells me that I have a multiple definition
of "head" and "tail"- without success.
edit: When the compiler gives the error message it opens up a locale_facets.tcc file
from I-don't-know-where and says that the error is on line 2497 in the following function:
bool
__verify_grouping(const char* __grouping, size_t __grouping_size,
const string& __grouping_tmp)
Does anyone have any insights?
Since this is homework, here is some information about queues and how you could go about implementing one.
A Queue is a standard Abstract Data Type.
It has several properties associated with it:
It is a linear data structure - all components are arranged in a straight line.
It has a grow/decay rule - queues add and remove from opposite ends.
Knowledge of how they're constructed shouldn't be integral in using them because they have public interfaces available.
Queues can be modeled using Sequential Arrays or Linked-Lists.
If you're using an array there are some things to consider because you grow in one direction so you will eventually run out of array. You then have some choices to make (shift versus grow). If you choose to shift back to the beginning of the array (wrap around) you have to make sure the head and tail don't overlap. If you choose to simply grow the queue, you have a lot of wasted memory.
If you're using a Linked-List, you can insert anywhere and the queue will grow from the tail and shrink from the head. You also don't have to worry about filling up your list and having to wrap/shift elements or grow.
However you decide to implement the queue, remember that Queues should provide some common interface to use the queue. Here are some examples:
enqueue - Inserts an element at the back (tail) of the queue
dequeue - Remove an element from the front (head) of a non-empty queue.
empty - Returns whether the queue is empty or not
size - Returns the size of the queue
There are other operations you might want to add to your queue (In C++, you may want an iterator to the front/back of your queue) but how you build your queue should not make a difference with regards to the operations it provides.
However, depending on how you want to use your queue, there are better ways to build it. The usual tradeoff is insert/removal time versus search time. Here is a decent reference.
If your assignment is not directly related to queue implementation, you might want to use the built in std::queue class in C++:
#include <queue>
void test() {
std::queue<int> myQueue;
myQueue.push(10);
if (myQueue.size())
myQueue.pop();
}
Why don't you just use the queue in standard C++ library?
#include <queue>
using namespace std;
int main() {
queue<int> Q;
Q.push(1);
Q.push(2);
Q.push(3);
Q.top(); // 1
Q.top(); // 1 again, we need to pop
Q.pop(); // void
Q.top(); // 2
Q.pop();
Q.top(); // 3
Q.pop();
Q.empty(); // true
return 0;
}
There are a couple of things wrong:
Your methods are declared as Enqueue and Dequeue, but defined as enqueue and dequeue: C++ is case sensitive.
Your methods refer to "heads" which doesn't appear to exist, do you mean "head"?
If you need this for BFS... just use deque.
#include <deque>
using namespace std;
void BFS() {
deque<GraphNode*> to_visit;
to_visit.push_back(start_node);
while (!to_visit.empty()) {
GraphNode* current = to_visit.front();
current->visit(&to_visit); // enqueues more nodes to visit with push_back
to_visit.pop_front();
}
}
The GraphNode::visit method should do all your "work" and add more nodes to the queue to visit. the only methods you should need are push_back(), front(), and pop_front()
This is how I always do it. Hope this helps.
It looks like your problem might have something to do with the fact that:
class Queue {
// blah
} *head, * tail;
is defining a Queue class, and declaring head and tail as type Queue*. They do not look like members of the class, which they should be.