似乎一个优先级队列只是一个具有正常队列操作(如insert,delete,top等)的堆.这是解释优先级队列的正确方法吗?我知道你可以以不同的方式构建优先级队列,但是如果要从堆构建优先级队列,则需要创建一个优先级队列,并给出构建堆和队列操作的指令,或者是否真的不需要构建班上?
我的意思是,如果我有一个功能来构建一个堆和函数来执行操作,如insert,我需要将所有这些函数放在一个类中,或者我可以使用指令,主要是调用它们.
我想我的问题是,是否有一个函数的集合相当于将它们存储在某个类中,并通过一个类使用它们,或者只是使用这些函数本身.
下面我是优先级队列实现的所有方法.这是否足以称之为实现,还是需要将其放在指定的优先级队列中?
- #ifndef MAX_PRIORITYQ_H
- #define MAX_PRIORITYQ_H
- #include <iostream>
- #include <deque>
- #include "print.h"
- #include "random.h"
- int parent(int i)
- {
- return (i - 1) / 2;
- }
- int left(int i)
- {
- if(i == 0)
- return 1;
- else
- return 2*i;
- }
- int right(int i)
- {
- if(i == 0)
- return 2;
- else
- return 2*i + 1;
- }
- void max_heapify(std::deque<int> &A,int i,int heapsize)
- {
- int largest;
- int l = left(i);
- int r = right(i);
- if(l <= heapsize && A[l] > A[i])
- largest = l;
- else
- largest = i;
- if(r <= heapsize && A[r] > A[largest])
- largest = r;
- if(largest != i) {
- exchange(A,i,largest);
- max_heapify(A,largest,heapsize);
- //int j = max_heapify(A,heapsize);
- //return j;
- }
- //return i;
- }
- void build_max_heap(std::deque<int> &A)
- {
- int heapsize = A.size() - 1;
- for(int i = (A.size() - 1) / 2; i >= 0; i--)
- max_heapify(A,heapsize);
- }
- int heap_maximum(std::deque<int> &A)
- {
- return A[0];
- }
- int heap_extract_max(std::deque<int> &A,int heapsize)
- {
- if(heapsize < 0)
- throw std::out_of_range("heap underflow");
- int max = A.front();
- //std::cout << "heapsize : " << heapsize << std::endl;
- A[0] = A[--heapsize];
- A.pop_back();
- max_heapify(A,heapsize);
- //int i = max_heapify(A,heapsize);
- //A.erase(A.begin() + i);
- return max;
- }
- void heap_increase_key(std::deque<int> &A,int key)
- {
- if(key < A[i])
- std::cerr << "New key is smaller than current key" << std::endl;
- else {
- A[i] = key;
- while(i > 1 && A[parent(i)] < A[i]) {
- exchange(A,parent(i));
- i = parent(i);
- }
- }
- }
- void max_heap_insert(std::deque<int> &A,int key)
- {
- int heapsize = A.size();
- A[heapsize] = std::numeric_limits<int>::min();
- heap_increase_key(A,heapsize,key);
- }
解决方法
有一个类完全符合你需要的接口(只是插入和弹出最大)有它的优点.
>稍后可以交换实现(例如,代替堆).
>读取使用队列的代码的人不需要了解堆数据结构中更难的接口.
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.
如果你只是想想“我的程序如何行为”,那么它是大部分相同的.但这并不等同于“人类读者对我的程序的理解”