关于网友提出的“ 高手帮忙看下这段代码,急(关于Heap和Priority Queue”问题疑问,本网通过在网上对“ 高手帮忙看下这段代码,急(关于Heap和Priority Queue”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: 高手帮忙看下这段代码,急(关于Heap和Priority Queue描述:
vector
以下的代码是利用Heap来实现Priority Queue, Priority Queue的文件应该没有问题,只是调用这里的函数而已。当我调用ExtractMin()的时候就会报错
#ifndef MIN_HEAP_H
#define MIN_HEAP_H
#include
using namespace std;
template
class min_heap
{
private:
vectorv;
int Parent (int index);
int LeftChild (int index);
int RightChild (int index);
void Heapify (vector& vec, int index);
void Build_Heap();
public:
min_heap ();
void Insert (T value);
// void HeapSort ();
T ExtractMin ();
T Minimum ();
void PrintHeap ();
};
template
min_heap::min_heap ()
{
v.resize(0);
}
template
int min_heap::Parent (int index)
{
if (index%2 == 0)
return (index - 1)/2;
else
return index / 2;
}
template
int min_heap::LeftChild (int index)
{
return 2 * index + 1;
}
template
int min_heap::RightChild (int index)
{
return 2 * index + 2;
}
template
void min_heap::Heapify (vector & vec, int index)
{
int left = LeftChild (index);
int right = RightChild (index);
int smallest;
T temp;
if (left <= int(vec.size()) - 1) //debug的时候,到了这里会报segmentation fault
{
if (vec[left] < vec[index])
smallest = left;
else
smallest = index;
}
if (right <= int(vec.size()) - 1) //debug的时候,到了这里会报segmentation fault
if (vec[right] < vec[smallest])
smallest = right;
if (smallest != index)
{
temp = vec[index];
vec[index] = vec[smallest];
vec[smallest] = temp;
Heapify(vec, smallest);
}
}
template
void min_heap::Build_Heap()
{
for (int i = (v.size()/2 - 1); i >= 0; i--)
Heapify(v, i);
}
template
void min_heap::Insert (T value)
{
v.push_back(value);
int i = v.size() - 1;
while (i > 0 && v[Parent(i)] > value)
{
v[i] = v[Parent(i)];
i = Parent(i);
}
v[i] = value;
}
template
T min_heap::ExtractMin ()
{
int smallest;
if (v.size() < 1)
cout << "Heap underflow" << endl;
else
{
smallest = v[0];
v[0] = v[v.size() - 1];
v.pop_back ();
Heapify(v, 0);
return smallest;
}
}
template
T min_heap::Minimum ()
{
if(!v.empty())
return v[0];
else
cout << "The heap is empty.";
}
template
void min_heap::PrintHeap ()
{
if (!v.empty())
{
for(int i = 0; i < int(v.size()); i++)
cout << v[i] << " ";
cout << endl;
}
else
cout << "The heap is empty.";
}
/*
template
void min_heap::HeapSort ()
{
T temp;
Build_Heap();
for (int i = v.size() - 1; i >= 1; i--)
{
temp = v[0];
v[0] = v[i];
v[i] = temp;
v.pop_back ();
Heapify (v, 0);
}
}
*/
#endif // MIN_HEAP_H
求各位大神帮我解惑一下,感激不尽
解决方案1:
smallest 没有初值,vec 为空的时候程序逻辑就错了。