简体   繁体   English

优先队列作为C ++中的堆

[英]Priority queue as heap in C++

I know there are some similar questions like this, but sadly none of them really match my problem... So I'm supposed to create a priority queue as heap. 我知道也有类似的问题,但是遗憾的是,没有一个问题真正符合我的问题……因此,我应该创建一个优先级队列作为堆。 We've been given some code snippets (rather pseudo code) to use, but if I print the tree, I won't get the correct numbers. 我们已经提供了一些代码片段(而不是伪代码)来使用,但是如果我打印树,我将得不到正确的数字。

I'm currently just trying to insert random numbers into the queue and print them. 我目前正试图将随机数插入队列并打印它们。 A queue element is a custom class named Queue_elem. 队列元素是名为Queue_elem的自定义类。 This is my insert function: 这是我的插入功能:

void Queue::insert(Queue_elem item){

  this->container[number_elements] = item;
  if (this->number_elements > 0) this->upHeap();
  this->number_elements++;
}

number_elements is the counter for the size of the array (container). number_elements是数组(容器)大小的计数器。 Here is my upHeap: 这是我的upHeap:

void Queue::upHeap(){
  for (int i = this->number_elements; i>=0; i = (i-1)/2) {
    int parent = (i-1)/2;
    if (this->container[i].getPriority() < this->container[parent].getPriority()) {
        swap(this->container[i], this->container[parent]);
    }
    break;
  }

} }

And that's it. 就是这样。 In my main I'm inserting random values and try to print them like this: 在我的主要内容中,我正在插入随机值,并尝试像这样打印它们:

Queue que(11);

mt19937 rng;
rng.seed(random_device()());
uniform_int_distribution<std::mt19937::result_type> dist6(1,50);
for (int i = 0; i < 10; ++i) {
    Queue_elem tmp(dist6(rng));
    que.insert(tmp);
}

cout << que.container[0].getPriority() << endl;
for (int i = 0; i < 5;i++) {

    cout << que.container[(2*i)+1].getPriority() << endl;
    cout << que.container[(2*i)+2].getPriority() << endl;
}

So I'm going through the tree child by child to print the array in the correct order, but it's always wrong... 所以我要逐个检查树以正确的顺序打印数组,但这总是错误的...

I can also provide the whole project if necessary. 如果需要,我也可以提供整个项目。 Thanks a bunch in advance. 预先感谢一堆。

Edit: Queue_elem 编辑:Queue_elem

class Queue_elem {
public:
    Queue_elem();
    Queue_elem(int prio);
    virtual ~Queue_elem();
    int getPriority();
    void setPriority(int prio);
    int getId();
private:
    int id;
    int priority;

}; };

Edit 2: The output is this: 编辑2:输出是这样的:

1
18
29
26
37
30
44
46
48 
49
0

I don't see a problem. 我没问题。 The output you show corresponds to this heap: 您显示的输出与此堆相对应:

              1
      18             29
  26      37     30      44
46  48  49

That's a valid min-heap. 那是一个有效的最小堆。 Every child node is larger than its parent. 每个子节点都大于其父节点。 Remember, in a heap, items aren't necessarily sorted. 请记住,在堆中,项目不一定要排序。

The reason you're getting a 0 at the end is because you're trying to print the right child of a node that has no right child. 最后得到0的原因是因为您试图打印没有正确子节点的节点的正确子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM