我正在使用数组实现来实现堆:
T* _heap = new T[HEAPSIZE];
int _n = 0; // number of elements in heap
但是,我无法比较这个数组中的项目:
template <class T>
void Heap<T>::_bubbleDown(int index) {
if (index << 1 + 1 > _n) {
_heap[0] = _heap[1];
return;
}
int left = index << 1;
int right = index << 1 + 1;
if (_heap[index] < _heap[left] && _heap[left] >= _heap[right]) {
swap(_heap[index], _heap[left]);
return _bubbleDown(left);
}
else if (_heap[index] < _heap[right] && _heap[right] >= _heap[left]) {
swap(_heap[index], _heap[right]);
return _bubbleDown(right);
}
_heap[0] = _heap[1];
}
在编译时返回
C2676: binary'<'; 'T' does not define this operator or a conversion to a type acceptable to the predefined operator
if 语句中的比较运算符。
我很困惑为什么会这样,考虑到我在网上看到代码,例如:
template<typename T>
T abs(T value) {
T result; // result's type is also T
result = (value >= 0) ? value : -value;
return result;
}
来自https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp8_Template.html似乎工作正常
为什么我会收到这个错误?我该如何解决?我的理解是T只是一个占位符类型,在程序实际运行中会被堆的数据类型代替,比如int,double,float等。所以我也觉得不可能通过
Unary operator>()
或类似的方式重载运算符。我说得对吗?