我正在尝试使用堆来实现模板化优先级队列来处理图像中像素的频率。它工作正常,但是当我尝试通过传递另一个类作为模板参数来使用它时,它最终会将该类转换为指向该类的指针,同时尝试向下或向上重新堆。这是堆规范:
template <typename ItemType>
struct HeapType
{
void ReheapDown(int, int);
void ReheapUp(int, int);
ItemType *elements;
int numElements;
};
重新堆下函数:
template<typename ItemType>
void HeapType<ItemType>::ReheapDown(int root, int bottom)
{
int maxChild, rightChild, leftChild;
leftChild = 2*root+1;
rightChild = 2*root+2;
if(leftChild <= bottom)
{
if(leftChild == bottom)
{
maxChild = leftChild;
}
else
{
if(elements[leftChild] <= elements[rightChild])
maxChild = rightChild;
else
maxChild = leftChild;
}
if(elements[root] < elements[maxChild])
{
Swap(elements, root, maxChild);
ReheapDown(maxChild, bottom);
}
}
}
和交换功能:
template<typename ItemType>
void Swap(ItemType &itemSwap, int swapFrom, int swapTo)
{
ItemType tempItem;
tempItem = itemSwap[swapFrom];
itemSwap[swapFrom] = itemSwap[swapTo];
itemSwap[swapTo] = tempItem;
}
因此,我使用名为 Pfreq 的辅助类来实现优先级队列,该类会重载比较运算符,以便堆按像素的频率而不是像素的值进行排序。它没有问题,直到到达 Swap 函数,然后提示它无法将类型从 Pfreq 转换为 Pfreq*。我不太确定如何解决模板导致 Swap 函数以 Pfreq* 类型调用的问题。
最佳答案
我认为问题出在这个函数的声明中:
template<typename ItemType>
void Swap(ItemType &itemSwap, int swapFrom, int swapTo)
您尝试将第一个参数用作数组,如下所示:
ItemType tempItem;
tempItem = itemSwap[swapFrom];
itemSwap[swapFrom] = itemSwap[swapTo];
itemSwap[swapTo] = tempItem;
问题在于 itemSwap
是对 ItemType
的引用,而不是 ItemType
的数组或指向 的指针项目类型
。尝试将该参数更改为 ItemType*
并查看是否可以解决问题。
希望这有帮助!
关于c++ - 模板化优先级队列导致对象成为指针。由 小码哥发布于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10200827/