我正在使用霍夫曼代码生成器。以下是我构建树的功能。该树基于对象指针的矢量。我已检查,它似乎工作正常。我现在想通过指针位置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对象的排序? –