1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
void buildHuffmanTree(string text, map<char, int> freq)
{
int arr[100];
int n = 0;
ifstream my_file1("text.txt");
if (my_file1.fail())
{
cout << "Failed to open this file!" << endl;
}
while (!my_file1.eof())
{
my_file1 >> arr[n];
n++;
}
my_file1.close();
//map<char, int> freq;
for (char ch : text)
{
freq[ch]++;
}
priority_queue<huffman_node*, vector<huffman_node*>, huffman_node> pq;
for (auto pair : freq)
{
pq.push(getNode(pair.first, pair.second, nullptr, nullptr));
}
while (pq.size() != 1)
{
huffman_node* left = pq.top(); pq.pop();
huffman_node* right = pq.top(); pq.pop();
int sum = left->priority + right->priority;
pq.push(getNode('\0', sum, left, right));
}
huffman_node* root = pq.top();
map<char, string> huffmanCode;
encode(root, "", huffmanCode);
cout << "char" << "\t\t" << "frequency" << "\t" << "encoding" << endl;
cout << "-----------------------------------------" << endl;
for (auto pair : huffmanCode)
{
cout << pair.first << "\t\t\t\t"<<pair.second << endl;
}
for (int i = 0; i < n-1; i++)
{
cout << "\t\t" << arr[i] << endl;
}
| |