我正在尝试为maxheap创建模板类,但我的代码中出现以下错误:
错误C2955:'堆':使用类模板需要模板参数 列表
我似乎很难理解为什么会这样。这是我的代码:
Heap.h
ifndef HEAP_H
#define HEAP_H
#include<vector>
template<class T>
class Heap{
protected:
std::vector<T>heap_arr;
int tempheap_size;
//int index;
int left;
int right;
int parent;
public:
Heap():tempheap_size(0), left(0), right(0), parent(0){}
void setLeft(int index){
left = 2 * index + 1;
}
void setRight(int index){
right = 2 * index + 2;
}
void setParent(int index){
parent = (index - 1) / 2;
}
virtual void heapsort()= 0;
virtual void insertElement(T val)= 0;
virtual void deleteElement(T val)= 0;
void swap(int index, int max){
T temp = heap_arr[index];
heap_arr[index] = heap_arr[max];
heap_arr[max] = temp;
}
int findElementIndex(T val, int index){
if (index == heap_arr.size())
cout << "Not found\n";
else if (heap_arr[index] == val)
return index;
else{
findElementIndex(val, index + 1);
}
}
void printHeap(){
for (int i = 0; i < heap_arr.size(); i++)
cout << heap_arr[i] << " ";
}
~Heap(){
}
};
#endif
Maxheap.h
#ifndef MAXHEAP_H
#define MAXHEAP_H
#include"Heap.h"
#include<vector>
template<class T>
class Maxheap:public Heap{
public:
Maxheap():Heap(){}
void copyHeap(T* arr, int size){
for (int i = 0; i < size; i++)
heap_arr.push_back(arr[i]);
tempheap_size = heap_arr.size();
}
void maxHeapify(int i){
setLeft(i);
setRight(i);
int max = i;
if (left < tempheap_size && heap_arr[left] > heap_arr[i])
max = left;
if (right < tempheap_size && heap_arr[right] > heap_arr[max])
max = right;
if (max != i){
swap(i, max);
maxHeapify(max);
}
}
void buildMaxHeap(){
for (int i = (heap_arr.size()) / 2 - 1; i >= 0; i--)
maxHeapify(i);
}
virtual void heapSort(){
//buildMaxHeap();
for (int i = heap_arr.size() - 1; i >= 1; i--){
swap(0, i);
tempheap_size--;
maxHeapify(0);
}
}
virtual void insertElement(T val){
heap_arr.push_back(val);
for (int i = heap_arr.size() - 1; i > 0; i = (i - 1) / 2){
setParent(i);
if (heap_arr[i] > heap_arr[parent])
swap(i, parent);
}
buildMaxHeap();
}
virtual void deleteElement(T val){
int i = 0;
i = findElementIndex(val, 0);
swap(i, heap_arr.size() - 1);
heap_arr.pop_back();
buildMaxHeap();
tempheap_size = heap_arr.size();
}
void printHeap(){
for (int i = 0; i < heap_arr.size(); i++)
cout << heap_arr[i] << " ";
}
~Maxheap(){
}
};
#endif
Main.cpp的
#include<iostream>
#include"Heap.h"
#include"Maxheap.h"
using namespace std;
int main(){
int size = 6;
int* arr = new int[size];
Maxheap<int> m_heap;
cout << "Enter array\n";
for (int i = 0; i < size; i++)
cin >> arr[i];
m_heap.copyHeap(arr, size);
cout << "Heap is: \n";
m_heap.printHeap();
cout << "\n";
m_heap.buildMaxHeap();
cout << "Heap is: \n";
m_heap.printHeap();
cout << "\n";
m_heap.heapSort();
cout << "Heap is: \n";
m_heap.printHeap();
m_heap.insertElement(50);
m_heap.insertElement(75);
m_heap.insertElement(500);
m_heap.deleteElement(25);
cout << "Heap is: \n";
m_heap.printHeap();
}
问题似乎在于:
template<class T>
class Maxheap:public Heap{
帮助将不胜感激。谢谢!