-
Notifications
You must be signed in to change notification settings - Fork 0
/
HCTree.hpp
71 lines (60 loc) · 1.98 KB
/
HCTree.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#ifndef HCTREE_HPP
#define HCTREE_HPP
#include <queue>
#include <vector>
#include <string>
#include "HCNode.hpp"
#include "BitInputStream.hpp"
#include "BitOutputStream.hpp"
using namespace std;
/** A 'function class' for use as the Compare class in a
* priority_queue<HCNode*>.
* For this to work, operator< must be defined to
* do the right thing on HCNodes.
*/
class HCNodePtrComp {
public:
bool operator()(HCNode*& lhs, HCNode*& rhs) const {
return *lhs < *rhs;
}
};
/** A Huffman Code Tree class.
* Not very generic: Use only if alphabet consists
* of unsigned chars.
*/
class HCTree {
private:
HCNode* root;
vector<HCNode*> leaves;
vector<string> value;
std::priority_queue<HCNode*, std::vector<HCNode*>, HCNodePtrComp> queue;
public:
explicit HCTree() : root(0) {
leaves = vector<HCNode*>(256, (HCNode*) 0);
value = vector<std::string>(256, std::string());
}
~HCTree();
/**
* Returns the value of the sequence to use as a reference later on.
*/
std::string getValue(byte bits) const;
/** Use the Huffman algorithm to build a Huffman coding trie.
* PRECONDITION: freqs is a vector of ints, such that freqs[i] is
* the frequency of occurrence of byte i in the message.
* POSTCONDITION: root points to the root of the trie,
* and leaves[i] points to the leaf node containing byte i.
*/
void build(const vector<int>& freqs);
/** Write to the given BitOutputStream
* the sequence of bits coding the given symbol.
* PRECONDITION: build() has been called, to create the coding
* tree, and initialize root pointer and leaves vector.
*/
void encode(byte symbol, BitOutputStream& out) const;
/** Return symbol coded in the next sequence of bits from the stream.
* PRECONDITION: build() has been called, to create the coding
* tree, and initialize root pointer and leaves vector.
*/
int decode(BitInputStream& in) const;
};
#endif // HCTREE_HPP