【发布时间】:2013-07-12 19:48:31
【问题描述】:
我正在开发 Huffman 代码生成器。下面是我组成树的函数。该树基于对象指针向量。我已经检查过了,它似乎工作正常。我现在想将位置 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 我在写完代码后考虑过。但除了效率之外,它是否有助于解决我在遍历树时遇到的问题? :-/
-
我很好奇.. 你的问题是 asciiChar 指针的排序而不是 asciiChar 对象的排序吗?
-
@PaulRenton, 不是真的,指针似乎排序很好这是我创建的排序函数: void vectSort2 (vector
&vect) //排序指针向量 { for (int i =0; i getCharCount() getCharCount()) { asciiChar * 临时 = vect[i]; vect[i] = vect[j]; vect[j] = 临时的; } } } } 我认为问题在于当我尝试遍历树为每个叶子生成代码时。 -
从根节点开始按顺序遍历的输出是什么
标签: c++ recursion traversal huffman-code