Код: Выделить всё
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <stdio.h>
using namespace std;
class Node {
public:
int a;
char c;
Node *left, *right;
Node (){};
Node (Node *L, Node *R)
{
left = L;
right = R;
a=L->a+R->a;
}
};
struct MyCompare
{
bool operator()(Node* l, Node* r) const
{
return l->a < r->a;
}
};
vector <bool> code;
map <char, vector<bool> > table;
map <char, vector<bool> >::iterator itrCode;
void BuildTable (Node *root)
{
if (root->left!=NULL)
{
code.push_back(0);
BuildTable (root->left);
}
if (root->right!=NULL)
{
code.push_back(1);
BuildTable (root->right);
}
if (root->c)
{
table[root->c]=code;
}
code.pop_back();
}
void print (Node* root, unsigned k=0)
{
if (root!=NULL)
{
print (root->left, k+3);
for (unsigned i=0; i<k; i++)
{
cout << " ";
}
if (root->c) cout << root->a << " (" << root->c << ") " << endl;
else cout << root->a <<endl;
print(root->right, k+3);
}
}
int main()
{
string s="Waiting for the san";
map <char, int> m;
for (int i=0; i<s.length(); i++)
{
char c=s[i];
m[c]++;
}
map <char, int>::iterator itr;
list<Node*> t;
for (itr=m.begin(); itr!=m.end(); itr++)
{
//cout << itr->first << ":" << itr->second << endl;
Node *p=new Node;
p->c=itr->first;
p->a=itr->second;
t.push_back(p);
}
while (t.size()!=1)
{
t.sort (MyCompare());
Node *SonL=t.front();
t.pop_front();
Node *SonR=t.front();
t.pop_front();
Node *parent = new Node(SonL, SonR);
t.push_back(parent);
}
Node *root=t.front();
//unsigned k=0;
//print (root, k);
BuildTable (root);
for (itrCode=table.begin(); itrCode!=table.end(); itrCode++)
{
cout << itrCode->first << itrCode->second;
}
}
Вот этот вывод который я пытался написать:
Код: Выделить всё
for (itrCode=table.begin(); itrCode!=table.end(); itrCode++)
{
cout << itrCode->first << itrCode->second;
}
Код: Выделить всё
cout << itrCode->first;