Huffman encoding and decoding C + + program __HTML5

Source: Internet
Author: User
Tags strcmp
huffman.h**********************//***************** leaves node for n of the Huffman tree has a total of 2n-1 nodes *******
    #ifndef huffman_h #define Huffman_h class Huffmannode {Public:char info;//node information double weight;//Node weights int parent, lchild, Rchild;
    Father Knot, left and right child node Huffmannode () {parent=lchild=rchild=-1; } huffmannode (const char &data, const double &WT, const int &pa=-1, const int &LCH=-1, const int &
        Rch=-1) {info=data;
        WEIGHT=WT;
        PARENT=PA;
        Lchild=lch;
    Rchild=rch; }
}; Class Huffmannode End Class Huffmantree {public:huffmantree (const int &s=100) {maxsize= (s&gt 
        ; 100?s:100);
        Arraytree=new Huffmannode[maxsize];
        currentsize=0;
    codearray=0;
        } ~huffmantree () {delete[] arraytree;
    if (codearray!=0) delete[] Codearray;

} void Run (const char*, const char*, const char*); Private:huffmannode *ARRAYTREe Huffman Knot points Group int maxSize; array maximum int currentsize; Current array size void insert (const char&, const double&); Insert node void Createhuffmantree (); Create Huffman tree void Createhuffmancode (); Create Huffman encoded int findposition (const char &) const; Returns the position of the character in arraytree[] int getlongestcodelength () const; Returns the maximum length encoded position int isequal (const char *s) const in the encoding system; Determine if s exists in the coding system, and if so, return the position of s in the encoding system, otherwise return-1 void print (); Print Huffman encoding private:class code {//huffmantree Private class, encoded Class Public:code (): Length (a) {ptr=new char[length] ;
        } ~code () {delete[] ptr;
        Char *ptr;
    const int length;
    }; Code *codearray;
The array size is currentsize void reverse (char arr[]); };  
Class Huffmantree end #endif//huffman.h End//**************************huffman.cpp********************** #include #include//for ofstream ifstream #include//for numeric_limits::max () #include//for exit () #include//for strlen (), S trcpy (), strcmp () #include "huffman.h" using namespace std; void Huffmantree::insert (const char &data, const double &WT) {//Insert node if (2*currentsize-1 >= maxSize)//Leaf knot
    Point for N Huffman tree A total of 2n-1 a node return;
    Arraytree[currentsize].info=data;
    ARRAYTREE[CURRENTSIZE].WEIGHT=WT;
currentsize++;
    } void Huffmantree::reverse (char arr[]) {//inverse string const int Len=strlen (ARR);
    Char *p;
    P=new char[len+1];
    strcpy (P, arr);
    P[len]= ' ";
    int k=0;
    for (int i=len-1; i>=0; i--) arr[i]=p[k++];
    Arr[len]= ' ";
Delete[] p; } int huffmantree::findposition (const char &ch) const {//return character ch position in arraytree[] for (int i=0; i<currentsize;
    i++) if (arraytree[i].info = = ch) return i;
return-1; int Huffmantree::getlongestcodelength () const {//Return encoded array codearray[] length of the encoded position if (currentsize = 0) returns
    -1;
    int Len=strlen (CODEARRAY[0].PTR);
    int i=1;
        while (I < currentsize) {int Tmp=strlen (CODEARRAY[I].PTR); if (tMP > Len) len=tmp;
    i++;
return Len; } int huffmantree::isequal (const char *s) const {//To determine if the encoding of S is present, if there is a position to return the encoding in the array codearray[], return-1 for (int i=0; I&LT;CU Rrentsize;
                i++) = "" If (strlen (s) = = strlen (codearray[i].ptr))//can remove this row if (strcmp (s, codearray[i].ptr) = 0)
    return i;
return-1;
    } void Huffmantree::p rint () {//print encoded int k=0; while (K < currentsize) {cout<<arraytree[k].info<< ' (' <<arraytree[k].weight<< '): "<&
        lt;codearray[k].ptr<<endl;
    k++;
    } void Huffmantree::createhuffmantree () {//constructs huffmantree int i=currentsize;
    int k;
    Double Wt1, wt2;
    int Lnode, Rnode;
        while (I < 2*currentsize-1) {Wt1=wt2=numeric_limits::max ();
        k=0;
                    while (K < i) {if (arraytree[k].parent==-1) {if (ARRAYTREE[K].WEIGHT&LT;WT1) {
                    WT2=WT1; Rnode=lnode;
                    Wt1=arraytree[k].weight;
                Lnode=k;
                    else if (arraytree[k].weight<wt2) {wt2=arraytree[k].weight;
                Rnode=k;
        }} k++;
        } arraytree[i].weight = Arraytree[lnode].weight+arraytree[rnode].weight;
        Arraytree[i].lchild=lnode;
        Arraytree[i].rchild=rnode;
        arraytree[lnode].parent=arraytree[rnode].parent=i;
    i++;
    } void Huffmantree::createhuffmancode () {//construct Huffmancode, that is Huffman encoding codearray=new code[currentsize];
    int i=0;
    int k, n, M;
        while (I < currentsize) {k = arraytree[i].parent;
        n=0;
        M=i; while (K!=-1 && k<currentsize*2-1) {if (arraytree[k].lchild==m) codearray[i].ptr[
            n++]= ' 0 ';
            else if (arraytree[k].rchild==m) codearray[i].ptr[n++]= ' 1 ';
       M=k;     K=arraytree[m].parent;
        } codearray[i].ptr[n]= '; Reverse (CODEARRAY[I].PTR);
    Reverse the string so that it becomes the correct encoding i++; } void Huffmantree::run (const char *infilename, const char *outfilename, const char *secondoutname) {//run function implementation//
    Open infilename to provide input ifstream Filein (Infilename, ios::in); if (!filein) {cerr<< "\" "<<infilename<<" \ "could=" "not=" "open."
        <<endl;
    Exit (1);
    } char ch;

    int POS;
    Reads characters from a file and counts the number of characters filein>>ch;
        while (Filein &&!filein.eof ()) {pos = findposition (CH);
        if (POS!=-1) arraytree[pos].weight++;
        else Insert (CH, 1);
    filein>>ch; } createhuffmantree (); Construct Huffman Tree Createhuffmancode ();
    Encode//Open outfilename for statistical characters to provide output ofstream fileout (Outfilename, ios::out); if (!fileout) {cerr<< "\" "<<outfilename<<" \ "could=" "not=" "open."
   <<endl;     Exit (1); } filein.clear ();

    Refresh the input stream, note: Ofstream has no flush () method, while Ifstream has flush () method FILEIN.SEEKG (0, Ios::beg);
    Encodes the characters from the Infilename file and writes them to the Outfilename file filein>>ch;
        while (Filein &&!filein.eof ()) {pos = findposition (CH);
        if (POS!=-1) fileout<<codearray[pos].ptr;
    filein>>ch;
    } filein.close ();

    Fileout.close ();
    Open Outfilename, secondoutname, respectively provide input and output filein.open (Outfilename, ios::in);
    Fileout.open (Secondoutname, ios::out); if (!filein | |!fileout) {cerr<< "File could not open."
        <<endl;
    Exit (1);
    ///decoding the encoding in the Outfilename file and writing the decoding result to the Secondoutname file const int longestlen = Getlongestcodelength ();
    Char *p = new char[longestlen+1];
    int k=0;
    filein>>ch;
            while (Filein &&!filein.eof ()) {if (K < Longestlen) {p[k++]=ch;
            P[k]= ' ";
            pos = IsEqual (P); if (pOS!=-1) {fileout<<arraytree[pos].info;
            k=0; } else {cerr<< "The code is wrong."
            <<endl;
        Exit (1);
    } filein>>ch;
    } filein.close ();
Fileout.close (); //huffman.cpp end//*****************************main.cpp************************* #include "Huffman.h" in
    T Main () {Huffmantree tree;
    const char *infilename= "In.txt";
    const char *infilename= "main.cpp";
    const char *outfilename= "Out1.txt";
    const char *secondoutname= "Out2.txt";
    Tree.run (Infilename, Outfilename, secondoutname);
return 0; }//main.cpp End


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.