C++實現哈夫曼編碼
阿新 • • 發佈:2020-04-28
本文例項為大家分享了C++實現哈夫曼編碼的具體程式碼,供大家參考,具體內容如下
#include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; int Max = 300; class tree{ public: char s; int num; tree *left; tree *right; tree(){ s= '!'; num = 0; left = 0; right = 0; } tree(char a,int n,tree* p1,tree* p2){ s = a; num = n; left = p1; right = p2; } }; vector<tree *> open; /********************************* **中序遍歷輸出各節點及其哈夫曼編碼 *********************************/ void inorder(tree *t,string s){ if(t != 0){ inorder(t->left,s+'0'); if(t->s != '!') cout<<t->s<<":"<<s<<endl; inorder(t->right,s+'1'); } } int main(){ int a[Max]; for(int i = 0;i < Max;i++) a[i] = 0; //初始化陣列 string s; cout<<"請輸入字串:"; cin>>s; vector<char> v; vector<char>::iterator vit; for(int i = 0;i < s.length();i ++){ a[s[i]]++; //確定每個字元出現的次數(頻率) vit = find(v.begin(),v.end(),s[i]); if(vit == v.end()) //相同的字元只保留一個 v.push_back(s[i]); } for(int i = 0;i < v.size();i ++){ tree *n = new tree(); n->s = v[i]; n->num = a[v[i]]; open.push_back(n); //存入open表中 } /************************ ** **構造哈夫曼樹 ** *************************/ tree *root; while(open.size() != 1){ tree *min1,*min2; //min1,min2是當前open表中num值最小的節點 int sit1,sit2; min1 = open.front(); sit1 = 0; for(int i = 0;i < open.size();i++){ if(open[i]->num < min1->num){ min1 = open[i]; sit1 = i; } } open.erase(open.begin()+sit1); min2 = open.front(); sit2 = 0; for(int i = 0;i < open.size();i++){ if(open[i]->num < min2->num){ min2 = open[i]; sit2 = i; } } open.erase(open.begin()+sit2); tree *t = new tree('!',min1->num + min2->num,min1,min2); //構造新節點,左右指標指min1和min2 open.push_back(t); //存入open表中 root = t; } cout<<"它的哈夫曼編碼為:"<<endl; string s1 = ""; inorder(root,s1); return 0; }```
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。