c – 优先级队列和堆之间的差异

前端之家收集整理的这篇文章主要介绍了c – 优先级队列和堆之间的差异前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
似乎一个优先级队列只是一个具有正常队列操作(如insert,delete,top等)的堆.这是解释优先级队列的正确方法吗?我知道你可以以不同的方式构建优先级队列,但是如果要从堆构建优先级队列,则需要创建一个优先级队列,并给出构建堆和队列操作的指令,或者是否真的不需要构建班上?

我的意思是,如果我有一个功能来构建一个堆和函数来执行操作,如insert,我需要将所有这些函数放在一个类中,或者我可以使用指令,主要是调用它们.

我想我的问题是,是否有一个函数的集合相当于将它们存储在某个类中,并通过一个类使用它们,或者只是使用这些函数本身.

下面我是优先级队列实现的所有方法.这是否足以称之为实现,还是需要将其放在指定的优先级队列中?

  1. #ifndef MAX_PRIORITYQ_H
  2. #define MAX_PRIORITYQ_H
  3. #include <iostream>
  4. #include <deque>
  5. #include "print.h"
  6. #include "random.h"
  7.  
  8. int parent(int i)
  9. {
  10. return (i - 1) / 2;
  11. }
  12.  
  13. int left(int i)
  14. {
  15. if(i == 0)
  16. return 1;
  17. else
  18. return 2*i;
  19. }
  20.  
  21. int right(int i)
  22. {
  23. if(i == 0)
  24. return 2;
  25. else
  26. return 2*i + 1;
  27. }
  28.  
  29. void max_heapify(std::deque<int> &A,int i,int heapsize)
  30. {
  31. int largest;
  32. int l = left(i);
  33. int r = right(i);
  34. if(l <= heapsize && A[l] > A[i])
  35. largest = l;
  36. else
  37. largest = i;
  38. if(r <= heapsize && A[r] > A[largest])
  39. largest = r;
  40. if(largest != i) {
  41. exchange(A,i,largest);
  42. max_heapify(A,largest,heapsize);
  43. //int j = max_heapify(A,heapsize);
  44. //return j;
  45. }
  46. //return i;
  47. }
  48.  
  49. void build_max_heap(std::deque<int> &A)
  50. {
  51. int heapsize = A.size() - 1;
  52. for(int i = (A.size() - 1) / 2; i >= 0; i--)
  53. max_heapify(A,heapsize);
  54. }
  55.  
  56. int heap_maximum(std::deque<int> &A)
  57. {
  58. return A[0];
  59. }
  60.  
  61. int heap_extract_max(std::deque<int> &A,int heapsize)
  62. {
  63. if(heapsize < 0)
  64. throw std::out_of_range("heap underflow");
  65. int max = A.front();
  66. //std::cout << "heapsize : " << heapsize << std::endl;
  67. A[0] = A[--heapsize];
  68. A.pop_back();
  69. max_heapify(A,heapsize);
  70. //int i = max_heapify(A,heapsize);
  71. //A.erase(A.begin() + i);
  72. return max;
  73. }
  74.  
  75. void heap_increase_key(std::deque<int> &A,int key)
  76. {
  77. if(key < A[i])
  78. std::cerr << "New key is smaller than current key" << std::endl;
  79. else {
  80. A[i] = key;
  81. while(i > 1 && A[parent(i)] < A[i]) {
  82. exchange(A,parent(i));
  83. i = parent(i);
  84. }
  85. }
  86. }
  87.  
  88. void max_heap_insert(std::deque<int> &A,int key)
  89. {
  90. int heapsize = A.size();
  91. A[heapsize] = std::numeric_limits<int>::min();
  92. heap_increase_key(A,heapsize,key);
  93. }

解决方法

有一个类完全符合你需要的接口(只是插入和弹出最大)有它的优点.

>稍后可以交换实现(例如,代替堆).
>读取使用队列的代码的人不需要了解堆数据结构中更难的接口.

I guess my question is whether having a collection of functions is
equivalent to storing them in some class and using them through a
class or just using the functions themselves.

如果你只是想想“我的程序如何行为”,那么它是大部分相同的.但这并不等同于“人类读者对我的程序的理解”

猜你在找的C&C++相关文章