我正在使用霍夫曼代碼生成器。以下是我構建樹的功能。該樹基於對象指針的矢量。我已檢查,它似乎工作正常。我現在想通過指針位置pointerVect [0]這應該是樹的根到我的Huffman編碼下面的遞歸函數,但由於某種原因,它不能正常工作,因爲當我嘗試打印的內容代碼存儲的地圖不會打印出來。霍夫曼編碼器 - 遞歸,編碼功能失敗
class asciiChar //Individual character module >>> Base Class
{
public:
void setCharValue (char letter)
{
charValue = letter;
}
char getCharValue()
{
return charValue;
}
void incrementCharCount()
{
charCount++;
}
int getCharCount()
{
return charCount;
}
virtual asciiChar * getLeft()
{
return left;
}
virtual asciiChar * getRight()
{
return right;
}
asciiChar(char c, int f) //Constructor
{
charValue = c;
charCount = f;
}
asciiChar & operator= (const asciiChar & other) //Overloaded assignment operator
{
charValue = other.charValue;
charCount = other.charCount;
return *this;
}
char charValue;
int charCount = 0;
asciiChar * left = NULL;
asciiChar * right = NULL;
};
class parentNode : public asciiChar //Connector node
{
public:
parentNode(asciiChar c0, asciiChar c1) : asciiChar(NULL, c0.getCharCount() + c1.getCharCount())
{
left = &c0;
right = &c1;
}
~parentNode()
{
if (left) delete left;
if (right) delete right;
}
};
asciiChar* createTree (vector<asciiChar> sortedVector)
{
vector<asciiChar*> pointerVect;
pointerVect.reserve(sortedVector.size());
for(int i=0; i < sortedVector.size(); i++)
{
pointerVect.push_back(new asciiChar(sortedVector[i].getCharValue(), sortedVector[i].getCharCount()));
}
while (pointerVect.size() > 1)
{
asciiChar * newL = pointerVect.back();
pointerVect.pop_back();
asciiChar * newR = pointerVect.back();
pointerVect.pop_back();
asciiChar * parent = new parentNode(* newL, * newR);
pointerVect.push_back(parent);
vectSort2 (pointerVect);
}
return pointerVect[0]; //Returns pointer at very top (The root of the tree)
}
你看着使用優先級隊列,而不是依賴你的載體,而每個循環迭代?對矢量排序爲O(nlog(n)),同時在優先級隊列中按照排序順序維護項目爲O(log(n))每個插入。 –
@PaulRenton我已經寫完我的代碼後想過它了。但除了效率之外,它還能幫助解決我在遍歷樹時遇到的問題嗎? : -/ – Gus
我很好奇..你的問題是asciiChar指針而不是asciiChar對象的排序? –