2012-04-17 80 views
2

我想實現一個模板優先級隊列使用堆來處理圖像中的像素的頻率。它工作正常,但是當我嘗試通過傳遞另一個類作爲模板參數來使用它時,它最終會將該類轉換爲指向該類的指針,同時嘗試重新堆疊或向上。這裏是堆規格:模板化優先級隊列,使對象成爲指針。 C++

template <typename ItemType> 
struct HeapType 
{ 
    void ReheapDown(int, int); 
    void ReheapUp(int, int); 
    ItemType *elements; 
    int numElements; 
}; 

reheap降功能:

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 *。我不完全確定如何解決模板導致使用Pfreq *類型調用Swap函數的問題。

回答

2

我認爲這個問題是在這個函數的聲明:

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的指針。嘗試更改該參數爲ItemType*,看看是否可以解決問題。

希望這會有所幫助!

+0

是的,就是這樣做的。謝謝! – Wenadin 2012-04-18 00:01:58