I have been stuck on this problem for many hours, but I have a feeling there is a trivial solution that I am not seeing. I am trying to use a priority_queue to create a MinHeap of pointers to a struct I defined. My issue lies in having to overload the > operator for the pointer to this struct (which I know is not possible) in order to match the priority_queue template. This is my last resort attempt to use the stl priority_queue before I decided to ditch it and write my own heap code.
The relevant snippets of my code are: (i) part the struct definition:
typedef struct Node Node;
struct Node
{
int frequency;
bool operator>( const Node& other ) const{
return frequency > other.frequency;
}
};
(ii) priority queue initialization:
priority_queue<Node*,vector<Node*>,greater<Node*> > q;
And (iii) the for loop constructing the initial heap (assume int_array has been initialized):
for (int i = 0; i < SIZEOFINTARRAY; i++)
{
Node *n = new Node;
n->frequency = int_array[i];
q.push(n);
}
Currently, the elements in this “heap” are returned FIFO, and no sorting happens. I assume this is because the priority comparison checks the pointer and elements earlier in an array are located lower in memory. Please give me any tips on how I could accomplish this.
PS. Sorry if this post does not adhere to stackoverflow standards (I tried my best to follow the rules but it is my first post). I welcome all criticism so I can never make the same mistakes again.
a generic way would be to implement a sort of
deref_greaterwhich is just likestd::greaterbut dereferences the input args first.