나는 허프만 인코딩을 프로그래밍하고 있습니다. 이것은 내 프로그램의 시작입니다 :우선 순위 대기열의 순서가 잘못됨
using namespace std;
//Counting methods
int *CountCharOccurence(string text)
{
int *charOccurrence = new int[127];
for(int i = 0; i < text.length(); i++)
{
charOccurrence[text[i]]++;
}
return charOccurrence;
}
void DisplayCharOccurence(int *charOccurrence)
{
for(int i = 0; i < 127; i++)
{
if(charOccurrence[i] > 0)
{
cout << (char)i << ": " << charOccurrence[i] << endl;
}
}
}
//Node struct
struct Node
{
public:
char character;
int occurrence;
Node(char c, int occ) {
character = c;
occurrence = occ;
}
bool operator < (const Node* node)
{
return (occurrence < node->occurrence);
}
};
void CreateHuffmanTree(int *charOccurrence)
{
priority_queue<Node*, vector<Node*> > pq;
for(int i = 0; i < 127; i++)
{
if(charOccurrence[i])
{
Node* node = new Node((char)i, charOccurrence[i]);
pq.push(node);
}
}
//Test
while(!pq.empty())
{
cout << "peek: " << pq.top()->character << pq.top()->occurrence << endl;
pq.pop();
}
}
int main(int argc, char** argv) {
int *occurrenceArray;
occurrenceArray = CountCharOccurence("SUSIE SAYS IT IS EASY");
DisplayCharOccurence(occurrenceArray);
CreateHuffmanTree(occurrenceArray);
return (EXIT_SUCCESS);
}
프로그램은 먼저 발생 숫자와 함께 문자를 출력합니다. 이것은 미세 같습니다
: 4 A: 2 E: 2 I: 3 S: 6 T: 1 U: 1 Y: 2
하지만 우선 순위 출력이 노드의 내용을 표시하는 테스트 루프 :
peek: Y2 peek: U1 peek: S6 peek: T1 peek: I3 peek: E2 peek: 4 peek: A2
이 예상 순서가 아니다. 왜?
Tnx 이제 작동합니다. 나는 잠시 동안 프로그램을하고 있지만 C++에 익숙하지 않다. 나는 당신이 언어를 더 잘 알수록 언어를 더 잘 알게 될 것입니다. 그러나 시작은 매우 어렵다고 생각합니다. – TheArchitect