C++實現(xiàn)哈夫曼編碼
更新時間:2020年04月28日 08:56:11 作者:南小唄
這篇文章主要為大家詳細介紹了C++實現(xiàn)哈夫曼編碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C++實現(xiàn)哈夫曼編碼的具體代碼,供大家參考,具體內(nèi)容如下
#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; /********************************* **中序遍歷輸出各節(jié)點及其哈夫曼編碼 *********************************/ 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; //初始化數(shù)組 string s; cout<<"請輸入字符串:"; cin>>s; vector<char> v; vector<char>::iterator vit; for(int i = 0;i < s.length();i ++){ a[s[i]]++; //確定每個字符出現(xiàn)的次數(shù)(頻率) 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表中 } /************************ ** **構(gòu)造哈夫曼樹 ** *************************/ tree *root; while(open.size() != 1){ tree *min1,*min2; //min1,min2是當前open表中num值最小的節(jié)點 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); //構(gòu)造新節(jié)點,左右指針指min1和min2 open.push_back(t); //存入open表中 root = t; } cout<<"它的哈夫曼編碼為:"<<endl; string s1 = ""; inorder(root,s1); return 0; }```
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C語言字符串函數(shù),字符函數(shù),內(nèi)存函數(shù)使用及模擬實現(xiàn)
這篇文章主要介紹了C語言字符串函數(shù),字符函數(shù),內(nèi)存函數(shù)使用及模擬實現(xiàn),文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09