1. 程式人生 > >LZW壓縮及解壓C++實現

LZW壓縮及解壓C++實現

##LZW演算法的壓縮與解壓 LZW壓縮

#include <iostream>
#include <string>
#include <map>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {//對編碼字元進行解碼 
	int n;
	map<int, string> LzwMap;  //定義鍵值對存放<code,string> 
	cout<<"輸入codes的個數"<<endl;
	cin>>n;
	int a[n];
	for(int i=0;i<n;i++){//輸入編碼後的數字 
		cout<<"第"<<i+1<<"個數字(編碼)";
		cin>>a[i];
	}
	LzwMap[1]="A",LzwMap[2]="B",LzwMap[3]="C";//初始化詞典分別對A/B/C進行1/2/3編碼
	string s="NIL";
	int count=4;//新字元的編碼 
	int k;
	string str;
	for(int i=0;i<n;i++){//對每一個給定的k進行查詢 
		k=a[i];
		map<int ,string>::iterator iter;
		bool flag=false;
		string value;
		for(iter=LzwMap.begin();iter!=LzwMap.end();iter++){//搜素字典中鍵為k的值 
			if (iter->first==k){
				flag=true;
				value=iter->second;
				break;	
			}	
		}
		if(flag==true){//若存在字典中,則輸出值 
			cout<<value<<"--";
		}
		if(s!="NIL"){//把S對應的字元和字典k中對應的字串的第一個字元相加並存儲在字典中 
			const char *p=value.data();
			str=s+p[0];
			LzwMap[count++]=str;	
		}
		s=value;
	}
	return 0;
}

LZW解壓

#include <iostream>
#include <string>
#include <map>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {//對編碼字元進行解碼
	int n;
	map<int, string> LzwMap;  //定義鍵值對存放<code,string>
	cout<<"輸入codes的個數"<<endl;
	cin>>n;
	int a[n];
	for(int i=0;i<n;i++){//輸入編碼後的數字
		cout<<"第"<<i+1<<"個數字(編碼)"<<endl;
		cin>>a[i];
	}
	LzwMap[1]="A",LzwMap[2]="B",LzwMap[3]="C";//初始化詞典分別對A/B/C進行1/2/3編碼
	string s="NIL";
	int count=4;//新字元的編碼
	int k;
	string str;
	for(int i=0;i<n;i++){//對每一個給定的k進行查詢
		k=a[i];
		map<int ,string>::iterator iter;
		bool flag=false;
		string value;
		for(iter=LzwMap.begin();iter!=LzwMap.end();iter++){//搜素字典中鍵為k的值
			if (iter->first==k){
				flag=true;
				value=iter->second;
				break;
			}
		}
		if(flag==true){//若存在字典中,則輸出值
			cout<<value<<"--";
		}
		if(s!="NIL"){//把S對應的字元和字典k中對應的字串的第一個字元相加並存儲在字典中
			const char *p=value.data();
			str=s+p[0];
			LzwMap[count++]=str;
		}
		s=value;
	}
	return 0;
}