C++ 密钥在二进制堆中的作用

C++ 密钥在二进制堆中的作用,c++,algorithm,data-structures,binary-heap,C++,Algorithm,Data Structures,Binary Heap,我在使用类的教科书中得到了这个二进制堆实现代码。但我不理解在构建堆时使用密钥的必要性 #define MAXREAL 999999.0 class HeapItem { public: int data; //actual data that is stored float key; //key value of the data, heap is constructed based on key }; class MinHeap { public: H

我在使用类的教科书中得到了这个二进制堆实现代码。但我不理解在构建堆时使用密钥的必要性

#define MAXREAL 999999.0

class HeapItem
{
    public:
    int data; //actual data that is stored
    float key; //key value of the data, heap is constructed based on key
};
class MinHeap
{
    public:
    HeapItem * A; //stores heap items, e.g., nodes
    int heapLength;
    int * map;

    MinHeap() //constructor
    {
        A = new HeapItem[MAX_HEAP_SIZE];
        map = new int[MAX_HEAP_SIZE];
        heapLength = 0;
    }
//Fills the heap with an array of integers
//key values do not maintain heap property
//May be used in some algorithms such as dijkstra's shortest path
    void initialize(int v[], int n)
    {
        heapLength = n;
        for (int i = 0; i<n; i++) //nodes are stored from index 1 instead of 0 in the heap
        {
            A[i + 1].data = v[i];
            A[i + 1].key = MAXREAL;
            map[v[i]] = i + 1; //map tracks which vertex is stored at which heap node
        }
    }
}
#定义MAXREAL 99999
类HeapItem
{
公众:
int data;//存储的实际数据
float key;//数据的key值,堆基于key构造
};
类MinHeap
{
公众:
HeapItem*A;//存储堆项目,例如节点
内厚;
int*地图;
MinHeap()//构造函数
{
A=新堆[MAX_HEAP_SIZE];
map=newint[MAX_HEAP_SIZE];
heapLength=0;
}
//用整数数组填充堆
//键值不维护堆属性
//可用于某些算法,如dijkstra最短路径
无效初始化(int v[],int n)
{
heapLength=n;

对于(int i=0;i在您的情况下,键不起任何作用,它甚至在注释中出现:

//key values do not maintain heap property
//May be used in some algorithms such as dijkstra's shortest path
还要注意的是,所有的键都被分配给了
MAXREAL
,基本上可以使用该键来

在您的情况下,这不能称为堆。因为未调用
Heapify
进程,并且没有对数组中的顺序进行假设。基本上,这意味着数据集中没有特定的顺序,因此这不是最小堆

此外,在堆中,元素从位置0(最小值)存储


看起来代码不完整或不正确

这里,堆树将基于
值构建

例如:此处红色框内的值为
,圆圈内的值为
数据

因为它是一个最小堆,所以它是基于
key
的值构建的。Root的
key
将小于它的子级。

断章取义,无法说明
key
字段的用途。你能给我们多一点代码,让我们看看它是如何使用的吗?我认为圆圈中的值是键。你给出的堆树是最大堆,不是最小堆。如果我错了,请纠正我。