Reputation: 396
I'm trying to implement a templated priority queue using a heap to process frequencies of pixels in an image. It works fine, but when I try to use it by passing another class as the template argument, it ends up converting the class to a pointer to the class while trying to reheap down or up. Here is the heap specification:
template <typename ItemType>
struct HeapType
{
void ReheapDown(int, int);
void ReheapUp(int, int);
ItemType *elements;
int numElements;
};
reheap down function:
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);
}
}
}
and Swap funciton:
template<typename ItemType>
void Swap(ItemType &itemSwap, int swapFrom, int swapTo)
{
ItemType tempItem;
tempItem = itemSwap[swapFrom];
itemSwap[swapFrom] = itemSwap[swapTo];
itemSwap[swapTo] = tempItem;
}
So, I have the Priority queue being implemented using a helper class called Pfreq that overloads the comparison operators so that the heap sorts by frequency of the pixel rather than the value of the pixel. It has no problem until it gets to the Swap function and then complains that it can't convert the type from Pfreq to Pfreq*. I'm not entirely sure how to solve the problem that the template causes the Swap function to be called with type Pfreq*.
Upvotes: 2
Views: 355
Reputation: 372814
I think the issue is in the declaration of this function:
template<typename ItemType>
void Swap(ItemType &itemSwap, int swapFrom, int swapTo)
You're trying to use the first argument as an array, as evidenced here:
ItemType tempItem;
tempItem = itemSwap[swapFrom];
itemSwap[swapFrom] = itemSwap[swapTo];
itemSwap[swapTo] = tempItem;
The problem is that itemSwap
is a reference to an ItemType
, not an array of ItemType
s or a pointer to an ItemType
. Try changing that parameter to be an ItemType*
and see if that fixes things.
Hope this helps!
Upvotes: 2