Using PriorityQueue

Hi I have a class with different variables like such
1
2
3
4
5
6
7
class Blocks
{
   public:
   string name;
   int ID;
   int time;
};


And I want to use a pointer to this class "Blocks" in a another class such as
1
2
3
4
5
6
7
 class PQ
{
  public:
   void loadQ(Blocks * bk); 
  private;
   priority_queue<Blocks *> pq;
};


My question is how does the priority Queue sort the Blocks *? More specifically how can I have it give one Block* a high priority solely base on the time variable? (I hope this is clear)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <string>
#include <queue>
#include <cassert>

struct block
{
   std::string name ;
   int id ;
   int time ;
};

struct cmp_blocks
{
    bool operator() ( const block& a, const block& b ) const
    { return a.time < b.time ; }

    bool operator() ( const block* const a, const block* const b ) const
    { assert( a && b ) ; return a->time < b->time ; }
};

std::priority_queue< block, std::vector<block>, cmp_blocks > pq1 ;

std::priority_queue< const block*, std::vector< const block* >, cmp_blocks > pq2 ;

Ninja'd. Oh, well
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <queue>
#include <ctime>
#include <cstdlib>

struct data
{
  int x;
  int y;

  data(int x, int y) : x(x), y(y) {}
};

std::ostream& operator<<(std::ostream& out, const data& d)
{  return out << d.x << " " << d.y;  }

struct comp_data
{
  bool operator() (const data* d1, const data* d2) const
  {
  if (d1->x == d2->x)
    return d1->y < d2->y;
  return d1->x < d2->x;
  }
};

int main (int argc, char **argv)
{
  srand(time(NULL));

  std::priority_queue<data*, std::vector<data*>, comp_data> p_queue;

  for (unsigned int i = 0; i < 20; i++)
    p_queue.push(new data(rand() % 10,rand() % 10));

  while (!p_queue.empty())
  {
    std::cout << *p_queue.top() << '\n';;
    delete p_queue.top();
    p_queue.pop();
  }
  return 0;
}


Maybe I could explain. If you had done this:
priority_queue<block> p_queue;
You would get a very long list of errors which all stem from there being no operator< for block. You could overload this operator if you wanted.
When you do this:
priority_queue<block*> p_queue;
You don't get any errors because the operator< is acting upon memory locations. It is a better idea to make a cmp_blocks, or comp_data, than to overload the < operator when dealing with pointers.

You have to add std::vector<block*> in there because it's simply the first of two deafault values in the priotity_queue's constructor.
Last edited on
Topic archived. No new replies allowed.