霍夫曼编码创建树C++
Huffman Coding Creating Tree C++
代码是更大解决方案的一部分。当我在 prioriQueue 中只有一个元素时,lastLeft 和 lastRight 是 nullptr。知道如何更改此算法以仅与一个元素一起工作,或者一些技巧如何更好地编写它吗?问题与评论"这是一个问题"一致。
std::shared_ptr<Leaf> HUFFMAN::TreeGenerating()
{
std::shared_ptr<Leaf> lastLeft = nullptr; // addr of last left child
std::shared_ptr<Leaf> lastRight = nullptr; // addr of last right child
while (!prioriQueue.empty())
{
std::shared_ptr<Leaf> rightChild = std::make_shared<Leaf>();
std::shared_ptr<Leaf> leftChild = std::make_shared<Leaf>();
std::shared_ptr<Leaf> nRoot = std::make_shared<Leaf>();
if (prioriQueue.size() == 1) // getting last element from prioriQueue, this if end algorithm
{
*nRoot = getElement();
nRoot->setLeftChild(lastLeft);
nRoot->setRightChild(lastRight);
nRoot->setFreq(lastLeft->getFreq() + lastRight->getFreq()); // HERE IS A PROBLEM !!
nRoot->setValue(0);
return nRoot;
}
else
{
*leftChild = getElement();
*rightChild = getElement();
nRoot->setLeftChild(leftChild);
nRoot->setRightChild(rightChild);
nRoot->setFreq(leftChild->getFreq() + rightChild->getFreq());
nRoot->setValue(0);
lastLeft = leftChild;
lastRight = rightChild;
InsertIntoQueue(*nRoot);
}
}
}
我会把它作为评论删除,因为 OP 的问题缺少太多信息以获得正确的答案,但它对于评论来说太复杂了。请注意,代码完全未经测试,因为需要太多假设。
OP已经大大复杂了。所需要的只是类似
std::shared_ptr<Leaf> HUFFMAN::TreeGenerating()
{
if (!prioriQueue.empty())
{
while (prioriQueue.size() > 1)
{
std::shared_ptr<Leaf> node = std::make_shared<Leaf>(getElement(),
getElement());
InsertIntoQueue(node);
}
return (getElement());
}
else
{
// handle the empty case
}
}
与 Leaf
构造函数类似如下:
Leaf::Leaf(std::shared_ptr<Leaf> right,
std::shared_ptr<Leaf> left)
{
rightChild = right;
leftChild = left;
freq = right->freq + left->freq
}
或使用成员初始值设定项列表
Leaf::Leaf(std::shared_ptr<Leaf> right,
std::shared_ptr<Leaf> left):
rightChild(right),
leftChild(left),
freq(right->freq + left->freq)
{
}
我还强烈建议重新考虑这种滥用std::shared_ptr
。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息