我有一个 C++ 程序,可以为文件中的所有字符创建霍夫曼代码。它运行良好,但我想在不使用 new 运算符的情况下创建节点,因为我知道您不应该使用它。我尝试使用向量全局变量来保存节点,但这不起作用。
std::vector<Node> nodes;
Node* create_node(unsigned char value, unsigned long long counter, Node* left, Node* right) {
Node temp;
temp.m_value = value;
temp.m_counter = counter;
temp.m_left = left;
temp.m_right = right;
nodes.push_back(temp);
return &nodes[nodes.size() - 1];
}
Run Code Online (Sandbox Code Playgroud)
编辑:我添加了更多代码,我没有真正解释什么不起作用。问题在于generate_code()
,它永远不会到达 nullptr。我也尝试使用 Node 而不是 Node* 但同样的事情发生了。
void generate_code(Node* current, std::string code, std::map<unsigned char, std::string>& char_codes) {
if (current == nullptr) {
return;
}
if (!current->m_left && !current->m_right) {
char_codes[current->m_value] = code;
}
generate_code(current->m_left, code + "0", char_codes);
generate_code(current->m_right, …
Run Code Online (Sandbox Code Playgroud)