Question: Help me implement the following c++ code: 1. function_one return a pointer to a root node of the Huffman tree for a sequence of keys
Help me implement the following c++ code:
1. function_one return a pointer to a root node of the Huffman tree for a sequence of keys in [first, last).
2. function_two should print to os huffman tree represented by the root.
3. function_three should release the entire memory used by tree root to insure no memory leaks
//------file_one--//////////////////////
#include
template bnode* function_one(Iter first, Iter last);
void function_two(std::ostream& os, node* root);
void function_three(node* root);
//------------end implementation file---//
//--------------main.cpp-------------//
#include symbol.hpp #include "file_one.hpp" #include #include #include #include #include
template void symbols(IterIn first, IterIn last, IterOut out) { std::vector count(256, 0);
for (; first != last; ++first) { const std::string& s = *first; for (int i = 0; i < s.size(); ++i) count[s[i]]++; } // for first
for (int c = 0; c < 256; ++c) { if (count[c] > 0) *out++ = symbol(static_cast(c), count[c]); } }
int main(int argc, char* argv[]) { if (argc != 2) { std::cout << "usage: ./a6 file" << std::endl; return -1; }
// get input text std::ifstream f(argv[1]);
std::string s; std::vector lines;
while (!f.eof()) { s = ""; std::getline(f, s); if (!s.empty()) lines.push_back(s); }
f.close();
std::vector A; symbols(lines.begin(), lines.end(), std::back_inserter(A));
//function calls node* tree = function_one(A.begin(), A.end()); function_two(std::cout, tree); function_three(tree);
return 0; }
//-----------------------end main.cpp----//
//-------------symbol.hpp----------------//
struct symbol { explicit symbol(char av = 0, int ac = 0) : value(av), count(ac) { } char value; // actual symbol, by default 0 (empty) int count; // count of the symbol, by default 0 };
// compare two symbols // symbol with a lower count is "less than" symbol with a higher count // symbols with equal count are compared lexicographically inline bool operator<(const symbol& lhs, const symbol& rhs) { return ((lhs.count < rhs.count) || (!(rhs.count < lhs.count) && (lhs.value < rhs.value))); } // operator<
template struct node { explicit node(const T& t = T(), node* l = nullptr, node* r = nullptr) : value(t), left_child(l), right_child(r) { }
T value;
node* left_child; node* right_child; };
//------------end symbol.cpp
test with a file contains the string BUAHAHAHAHAAAAAA
the output should be
B 000 U 001 H 01 A 1
output's order is irrelevant
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
