我试图在我的向量“ heapvect”中插入一个数字。我一直在更改引用和指针,但仍然不允许我将num传递给向量。我已经在没有模板的情况下创建了这个数组,并创建了一个动态数组(构造函数/析构函数),但不确定是否有矢量和模板使我对整个堆排序有不同的看法。
我尝试使用heapvect和getheapvect的指针。
//main.cpp
#include"heap.h"
#include<iostream>
#include<vector>
using namespace std;
int main() {
int size;
int num;
cout << "USER:" << endl;
cout << "Enter size for heap: " << endl;
cin >> size;
heap<class T> yeet;
cout << "Enter in " << size << " of items:" << endl;
for (int i = 0; i < size; i++) {
cin >> num;
yeet.getheapvect().push_back(num);
}
system("pause");
return 0;
}
//heap.cpp
#include "heap.h"
template<class T>
heap<T>::heap() {
}
template<class T>
heap<T>::heap(int size) {
getheapvect().resize(size*2);
}
template<class T>
heap<T>::~heap() {
}
template<class T>
void heap<T>::insertin(const T item) {
getheapvect().push_back(item);
int index = distance(getheapvect().begin(), item);
while (index != 0 && getheapvect()[parent(index)] > getheapvect()[index]) {
swap(getheapvect[index], getheapvect()[parent(index)]);
index = parent(index);
}
}
template<class T>
void heap<T>::minheap(int size, int index) {
int large = index;
int left = (2 * index) + 1;
int right = (2 * index) + 2;
if (left < size && getheapvect()[left]>getheapvect()[large])
large = left;
if (right < size && getheapvect()[right]>getheapvect()[large])
large = right;
if (large != index) {
swap(getheapvect()[index], getheapvect()[large]);
makeheap(size, large);
}
}
template<class T>
void heap<T>::heapsort(int size) {
for (int i = (size / 2) - 1; i >= 0; i--)
makeheap(size, i);
for (int i = size - 1; i >= 0; i--) {
swap(getheapvect()[0], getheapvect()[i]);
makeheap(i, 0);
}
}
template<class T>
void heap<T>::print(int size) {
for (int i = 0; i < size; i++)
cout << getheapvect()[i] << ' ';
cout << endl;
}
template<class T>
void heap<T>::PRINT() {
print(getheapvect().size());
}
template<class T>
void heap<T>::swap(T a, T b) {
T temp = a;
a = b;
b = temp;
}
//heap.h
#ifndef HEAP_H
#define HEAP_H
#include<iostream>
#include<vector>
using namespace std;
template<class T>
class heap {
private:
vector<T> heapvect;
void print(int size);
public:
heap();
heap(int size);
~heap();
void insertin(const T item);
void minheap(int size, int index);
void heapsort(int size);
void PRINT();
void swap(T a, T b);
int parent(int i) { return ((i - 1) / 2); };
int leftchild(int i) { return ((2 * i) + 1); };
int rightchild(int i) { return ((2 * i) + 2); };
vector<T>& getheapvect(){ return heapvect; };
};
#endif
输出应该按升序带出排序的向量。
答案 0 :(得分:0)
准备使用类模板时,需要提供可用于实例化它的类型。
在main
中,而不是
heap<class T> yeet;
使用
heap<int> yeet;