Huffman Code in C++Singly linked list classGame of Life improvementHuffman decoding for videoMax heap in JavaHuffman code implementationHuffman code generator in HaskellGeneric Pairing Heap PerformanceHuffman code generator in TypescriptC++ Huffman coder and decoderHuffman Coding in C++Calculating the number of rooms in a 2D houseC++11 min-heap with configurable arity

Why are lawsuits between the President and Congress not automatically sent to the Supreme Court

Why do academics prefer Mac/Linux?

Why did Varys remove his rings?

Is it possible to pass a pointer to an operator as an argument like a pointer to a function?

Write electromagnetic field tensor in terms of four-vector potential

I recently started my machine learning PhD and I have absolutely no idea what I'm doing

How can I safely determine the output voltage and current of a transformer?

Is there a method to separate iron from mercury?

Does a non-singular matrix have a large minor with disjoint rows and columns and full rank?

Do we see some Unsullied doing this in S08E05?

How can I fix the label locations on my tikzcd diagram?

Why is vowel phonology represented in a trapezoid instead of a square?

Why use a retrograde orbit?

Do high-wing aircraft represent more difficult engineering challenges than low-wing aircraft?

Promotion comes with unexpected 24/7/365 on-call

Why is so much ransomware breakable?

Failing students when it might cause them economic ruin

Was the dragon prowess intentionally downplayed in S08E04?

multiline equation inside a matrix that is a part of multiline equation

How to handle professionally if colleagues has referred his relative and asking to take easy while taking interview

Why are there five extra turns in tournament Magic?

How to deal with the extreme reverberation in big cathedrals when playing the pipe organs?

Would a "ring language" be possible?

Cannot remove door knob -- totally inaccessible!



Huffman Code in C++


Singly linked list classGame of Life improvementHuffman decoding for videoMax heap in JavaHuffman code implementationHuffman code generator in HaskellGeneric Pairing Heap PerformanceHuffman code generator in TypescriptC++ Huffman coder and decoderHuffman Coding in C++Calculating the number of rooms in a 2D houseC++11 min-heap with configurable arity






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6












$begingroup$


This is my version of the Huffman Codes.



/*
Author: Stevan Milic
Date: 05.05.2018.
Course: Data Structures II
Professor: Dr. Claude Chaudet
Description: Huffman Codes
*/
#include <iostream>
#include <cstdlib>
using namespace std;
#define MAX_TREE_HEIGHT 1000

// A Huffman tree node
struct MinHeapNode

char codeword; // I chose char because we are inputing alphabetic letters

// The reason why I chose unsigned data type is because an unsigned integer can never be negative.
// In this case the frequency and the capacity of a character cannot be negative.
unsigned freq; // Frequency of the character - how many times does it occur

struct MinHeapNode *left, *right; // Left and Right children
;

struct MinHeap // Collection of nodes

unsigned size; // Size of the heap
unsigned capacity; // Capacity of the heap
struct MinHeapNode** array; // Heap node pointers array
;

// Function to dynamically alocate a new heap node with provided character (codeword) and its frequency
struct MinHeapNode* newHeapNode(char codeword, unsigned freq)

struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode));

temp->left = temp->right = NULL;
temp->codeword = codeword;
temp->freq = freq;

return temp;


// Creating a new dynamically allocated min heap with given capacity
struct MinHeap* createMinHeap(unsigned capacity)

struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap));
minHeap->size = 0; // Setting the size to 0
minHeap->capacity = capacity; // Inserting the given capacity
// Inserting into the heap node pointers array
minHeap->array= (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode*));
return minHeap;


// Swap function to swap two min heap nodes
void swap(struct MinHeapNode** a, struct MinHeapNode** b)

struct MinHeapNode* temp2 = *a;
*a = *b;
*b = temp2;

// minHeapify function
void minHeapify(struct MinHeap* minHeap, int index)

int smallest = index;
int leftSon = 2 * index + 1;
int rightSon = 2 * index + 2;

if (leftSon < minHeap->size && minHeap->array[leftSon]->freq < minHeap->array[smallest]->freq)
smallest = leftSon;

if (rightSon < minHeap->size && minHeap->array[rightSon]-> freq < minHeap->array[smallest]->freq)
smallest = rightSon;

if (smallest != index)

swap(&minHeap->array[smallest], &minHeap->array[index]);
minHeapify(minHeap, smallest);



// Checking if the size of the heap is 1
int heapSizeOne(struct MinHeap* minHeap)

return (minHeap->size == 1);


// Extracting minimum value node from the heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap)

struct MinHeapNode* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
--minHeap->size;
minHeapify(minHeap, 0);
return temp;


// Inserting a new node into min heap
void insert(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode)

++minHeap->size;
int i = minHeap->size - 1;
while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq)

minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;

minHeap->array[i] = minHeapNode;


// Build function to build min heap
void build(struct MinHeap* minHeap)

int n = minHeap->size - 1;
for (int i = (n - 1) / 2; i >= 0; --i)
minHeapify(minHeap, i);


// Display function to print an array
void display(int arr[], int n)

int i;
for (i = 0; i < n; ++i)
cout << arr[i];
cout << "n";


// Function to check if the node is a leaf
int isLeaf(struct MinHeapNode* root)

return !(root->left) && !(root->right);



// Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency.
struct MinHeap* create(char codeword[], int freq[], int size)

struct MinHeap* minHeap = createMinHeap(size);
for (int i = 0; i < size; ++i)
minHeap->array[i] = newHeapNode(codeword[i], freq[i]);
minHeap->size = size;
build(minHeap);
return minHeap;


// Function that builds the Huffman tree
struct MinHeapNode* buildHT(char codeword[], int freq[], int size)

struct MinHeapNode *left, *right, *top;

// Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency.
struct MinHeap* minHeap = create(codeword, freq, size);

// while loop runs as long as the size of heap doesn't reach 1
while (!heapSizeOne(minHeap))

// Getting the two minimums from min heap
left = extractMin(minHeap);
right = extractMin(minHeap);

// The frequency of top is computed as the sum of the frequencies of left and right nodes.
top = newHeapNode('_', left->freq + right->freq);
top->left = left;
top->right = right;
insert(minHeap, top);

// The remaining value is the root node which completes the tree
return extractMin(minHeap);


// Prints huffman codes from the root of
// Displaying Huffman codes
void displayHC(struct MinHeapNode* root, int arr[], int top)


// Left side is given the value 0
if (root->left)

arr[top] = 0;
displayHC(root->left, arr, top + 1);

// Right side is given the value 1
if (root->right)

arr[top] = 1;
displayHC(root->right, arr, top + 1);

// If this is a leaf node, print the character and its code.
if (isLeaf(root))

cout << root->codeword << ": ";
display(arr, top);



// Building a Huffman Tree and displaying the codes
void HuffmanCodes(char codeword[], int freq[], int size)


// Building a HT
struct MinHeapNode* root = buildHT(codeword, freq, size);

// Displaying the HT we built
int arr[MAX_TREE_HEIGHT], top = 0;

displayHC(root, arr, top);


// I used the example from the PP presentation in the Files section - The Hoffman Coding
int main()
4t B









share|improve this question











$endgroup$







  • 16




    $begingroup$
    Your code is pretty much "C with cout and using namespace std;s". It doesn't look like C++ at all.
    $endgroup$
    – L. F.
    May 5 at 10:36






  • 6




    $begingroup$
    Is this code for an assignment? I'd recommend not putting it online if you haven't yet had it graded.
    $endgroup$
    – TEK
    May 5 at 10:40







  • 10




    $begingroup$
    You seem to make the same mistakes over and over again. Could I suggest you consider using some of the answers you are receiving.
    $endgroup$
    – bruglesco
    May 5 at 20:19










  • $begingroup$
    It looks like you have two different things going on here: A min heap data structure, and an implementation of a huffman code algorithm that happens to use a min heap. Don't conflate the two. Build a generic min heap (that'll come in useful in other places), and build a separate huffman code function that uses it.
    $endgroup$
    – Alexander
    May 6 at 2:32










  • $begingroup$
    Which version of C++ are you using? (command line parameters or compiler version would be useful )
    $endgroup$
    – Robert Andrzejuk
    May 6 at 8:17


















6












$begingroup$


This is my version of the Huffman Codes.



/*
Author: Stevan Milic
Date: 05.05.2018.
Course: Data Structures II
Professor: Dr. Claude Chaudet
Description: Huffman Codes
*/
#include <iostream>
#include <cstdlib>
using namespace std;
#define MAX_TREE_HEIGHT 1000

// A Huffman tree node
struct MinHeapNode

char codeword; // I chose char because we are inputing alphabetic letters

// The reason why I chose unsigned data type is because an unsigned integer can never be negative.
// In this case the frequency and the capacity of a character cannot be negative.
unsigned freq; // Frequency of the character - how many times does it occur

struct MinHeapNode *left, *right; // Left and Right children
;

struct MinHeap // Collection of nodes

unsigned size; // Size of the heap
unsigned capacity; // Capacity of the heap
struct MinHeapNode** array; // Heap node pointers array
;

// Function to dynamically alocate a new heap node with provided character (codeword) and its frequency
struct MinHeapNode* newHeapNode(char codeword, unsigned freq)

struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode));

temp->left = temp->right = NULL;
temp->codeword = codeword;
temp->freq = freq;

return temp;


// Creating a new dynamically allocated min heap with given capacity
struct MinHeap* createMinHeap(unsigned capacity)

struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap));
minHeap->size = 0; // Setting the size to 0
minHeap->capacity = capacity; // Inserting the given capacity
// Inserting into the heap node pointers array
minHeap->array= (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode*));
return minHeap;


// Swap function to swap two min heap nodes
void swap(struct MinHeapNode** a, struct MinHeapNode** b)

struct MinHeapNode* temp2 = *a;
*a = *b;
*b = temp2;

// minHeapify function
void minHeapify(struct MinHeap* minHeap, int index)

int smallest = index;
int leftSon = 2 * index + 1;
int rightSon = 2 * index + 2;

if (leftSon < minHeap->size && minHeap->array[leftSon]->freq < minHeap->array[smallest]->freq)
smallest = leftSon;

if (rightSon < minHeap->size && minHeap->array[rightSon]-> freq < minHeap->array[smallest]->freq)
smallest = rightSon;

if (smallest != index)

swap(&minHeap->array[smallest], &minHeap->array[index]);
minHeapify(minHeap, smallest);



// Checking if the size of the heap is 1
int heapSizeOne(struct MinHeap* minHeap)

return (minHeap->size == 1);


// Extracting minimum value node from the heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap)

struct MinHeapNode* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
--minHeap->size;
minHeapify(minHeap, 0);
return temp;


// Inserting a new node into min heap
void insert(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode)

++minHeap->size;
int i = minHeap->size - 1;
while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq)

minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;

minHeap->array[i] = minHeapNode;


// Build function to build min heap
void build(struct MinHeap* minHeap)

int n = minHeap->size - 1;
for (int i = (n - 1) / 2; i >= 0; --i)
minHeapify(minHeap, i);


// Display function to print an array
void display(int arr[], int n)

int i;
for (i = 0; i < n; ++i)
cout << arr[i];
cout << "n";


// Function to check if the node is a leaf
int isLeaf(struct MinHeapNode* root)

return !(root->left) && !(root->right);



// Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency.
struct MinHeap* create(char codeword[], int freq[], int size)

struct MinHeap* minHeap = createMinHeap(size);
for (int i = 0; i < size; ++i)
minHeap->array[i] = newHeapNode(codeword[i], freq[i]);
minHeap->size = size;
build(minHeap);
return minHeap;


// Function that builds the Huffman tree
struct MinHeapNode* buildHT(char codeword[], int freq[], int size)

struct MinHeapNode *left, *right, *top;

// Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency.
struct MinHeap* minHeap = create(codeword, freq, size);

// while loop runs as long as the size of heap doesn't reach 1
while (!heapSizeOne(minHeap))

// Getting the two minimums from min heap
left = extractMin(minHeap);
right = extractMin(minHeap);

// The frequency of top is computed as the sum of the frequencies of left and right nodes.
top = newHeapNode('_', left->freq + right->freq);
top->left = left;
top->right = right;
insert(minHeap, top);

// The remaining value is the root node which completes the tree
return extractMin(minHeap);


// Prints huffman codes from the root of
// Displaying Huffman codes
void displayHC(struct MinHeapNode* root, int arr[], int top)


// Left side is given the value 0
if (root->left)

arr[top] = 0;
displayHC(root->left, arr, top + 1);

// Right side is given the value 1
if (root->right)

arr[top] = 1;
displayHC(root->right, arr, top + 1);

// If this is a leaf node, print the character and its code.
if (isLeaf(root))

cout << root->codeword << ": ";
display(arr, top);



// Building a Huffman Tree and displaying the codes
void HuffmanCodes(char codeword[], int freq[], int size)


// Building a HT
struct MinHeapNode* root = buildHT(codeword, freq, size);

// Displaying the HT we built
int arr[MAX_TREE_HEIGHT], top = 0;

displayHC(root, arr, top);


// I used the example from the PP presentation in the Files section - The Hoffman Coding
int main()
4t B









share|improve this question











$endgroup$







  • 16




    $begingroup$
    Your code is pretty much "C with cout and using namespace std;s". It doesn't look like C++ at all.
    $endgroup$
    – L. F.
    May 5 at 10:36






  • 6




    $begingroup$
    Is this code for an assignment? I'd recommend not putting it online if you haven't yet had it graded.
    $endgroup$
    – TEK
    May 5 at 10:40







  • 10




    $begingroup$
    You seem to make the same mistakes over and over again. Could I suggest you consider using some of the answers you are receiving.
    $endgroup$
    – bruglesco
    May 5 at 20:19










  • $begingroup$
    It looks like you have two different things going on here: A min heap data structure, and an implementation of a huffman code algorithm that happens to use a min heap. Don't conflate the two. Build a generic min heap (that'll come in useful in other places), and build a separate huffman code function that uses it.
    $endgroup$
    – Alexander
    May 6 at 2:32










  • $begingroup$
    Which version of C++ are you using? (command line parameters or compiler version would be useful )
    $endgroup$
    – Robert Andrzejuk
    May 6 at 8:17














6












6








6


2



$begingroup$


This is my version of the Huffman Codes.



/*
Author: Stevan Milic
Date: 05.05.2018.
Course: Data Structures II
Professor: Dr. Claude Chaudet
Description: Huffman Codes
*/
#include <iostream>
#include <cstdlib>
using namespace std;
#define MAX_TREE_HEIGHT 1000

// A Huffman tree node
struct MinHeapNode

char codeword; // I chose char because we are inputing alphabetic letters

// The reason why I chose unsigned data type is because an unsigned integer can never be negative.
// In this case the frequency and the capacity of a character cannot be negative.
unsigned freq; // Frequency of the character - how many times does it occur

struct MinHeapNode *left, *right; // Left and Right children
;

struct MinHeap // Collection of nodes

unsigned size; // Size of the heap
unsigned capacity; // Capacity of the heap
struct MinHeapNode** array; // Heap node pointers array
;

// Function to dynamically alocate a new heap node with provided character (codeword) and its frequency
struct MinHeapNode* newHeapNode(char codeword, unsigned freq)

struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode));

temp->left = temp->right = NULL;
temp->codeword = codeword;
temp->freq = freq;

return temp;


// Creating a new dynamically allocated min heap with given capacity
struct MinHeap* createMinHeap(unsigned capacity)

struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap));
minHeap->size = 0; // Setting the size to 0
minHeap->capacity = capacity; // Inserting the given capacity
// Inserting into the heap node pointers array
minHeap->array= (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode*));
return minHeap;


// Swap function to swap two min heap nodes
void swap(struct MinHeapNode** a, struct MinHeapNode** b)

struct MinHeapNode* temp2 = *a;
*a = *b;
*b = temp2;

// minHeapify function
void minHeapify(struct MinHeap* minHeap, int index)

int smallest = index;
int leftSon = 2 * index + 1;
int rightSon = 2 * index + 2;

if (leftSon < minHeap->size && minHeap->array[leftSon]->freq < minHeap->array[smallest]->freq)
smallest = leftSon;

if (rightSon < minHeap->size && minHeap->array[rightSon]-> freq < minHeap->array[smallest]->freq)
smallest = rightSon;

if (smallest != index)

swap(&minHeap->array[smallest], &minHeap->array[index]);
minHeapify(minHeap, smallest);



// Checking if the size of the heap is 1
int heapSizeOne(struct MinHeap* minHeap)

return (minHeap->size == 1);


// Extracting minimum value node from the heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap)

struct MinHeapNode* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
--minHeap->size;
minHeapify(minHeap, 0);
return temp;


// Inserting a new node into min heap
void insert(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode)

++minHeap->size;
int i = minHeap->size - 1;
while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq)

minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;

minHeap->array[i] = minHeapNode;


// Build function to build min heap
void build(struct MinHeap* minHeap)

int n = minHeap->size - 1;
for (int i = (n - 1) / 2; i >= 0; --i)
minHeapify(minHeap, i);


// Display function to print an array
void display(int arr[], int n)

int i;
for (i = 0; i < n; ++i)
cout << arr[i];
cout << "n";


// Function to check if the node is a leaf
int isLeaf(struct MinHeapNode* root)

return !(root->left) && !(root->right);



// Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency.
struct MinHeap* create(char codeword[], int freq[], int size)

struct MinHeap* minHeap = createMinHeap(size);
for (int i = 0; i < size; ++i)
minHeap->array[i] = newHeapNode(codeword[i], freq[i]);
minHeap->size = size;
build(minHeap);
return minHeap;


// Function that builds the Huffman tree
struct MinHeapNode* buildHT(char codeword[], int freq[], int size)

struct MinHeapNode *left, *right, *top;

// Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency.
struct MinHeap* minHeap = create(codeword, freq, size);

// while loop runs as long as the size of heap doesn't reach 1
while (!heapSizeOne(minHeap))

// Getting the two minimums from min heap
left = extractMin(minHeap);
right = extractMin(minHeap);

// The frequency of top is computed as the sum of the frequencies of left and right nodes.
top = newHeapNode('_', left->freq + right->freq);
top->left = left;
top->right = right;
insert(minHeap, top);

// The remaining value is the root node which completes the tree
return extractMin(minHeap);


// Prints huffman codes from the root of
// Displaying Huffman codes
void displayHC(struct MinHeapNode* root, int arr[], int top)


// Left side is given the value 0
if (root->left)

arr[top] = 0;
displayHC(root->left, arr, top + 1);

// Right side is given the value 1
if (root->right)

arr[top] = 1;
displayHC(root->right, arr, top + 1);

// If this is a leaf node, print the character and its code.
if (isLeaf(root))

cout << root->codeword << ": ";
display(arr, top);



// Building a Huffman Tree and displaying the codes
void HuffmanCodes(char codeword[], int freq[], int size)


// Building a HT
struct MinHeapNode* root = buildHT(codeword, freq, size);

// Displaying the HT we built
int arr[MAX_TREE_HEIGHT], top = 0;

displayHC(root, arr, top);


// I used the example from the PP presentation in the Files section - The Hoffman Coding
int main()
4t B









share|improve this question











$endgroup$




This is my version of the Huffman Codes.



/*
Author: Stevan Milic
Date: 05.05.2018.
Course: Data Structures II
Professor: Dr. Claude Chaudet
Description: Huffman Codes
*/
#include <iostream>
#include <cstdlib>
using namespace std;
#define MAX_TREE_HEIGHT 1000

// A Huffman tree node
struct MinHeapNode

char codeword; // I chose char because we are inputing alphabetic letters

// The reason why I chose unsigned data type is because an unsigned integer can never be negative.
// In this case the frequency and the capacity of a character cannot be negative.
unsigned freq; // Frequency of the character - how many times does it occur

struct MinHeapNode *left, *right; // Left and Right children
;

struct MinHeap // Collection of nodes

unsigned size; // Size of the heap
unsigned capacity; // Capacity of the heap
struct MinHeapNode** array; // Heap node pointers array
;

// Function to dynamically alocate a new heap node with provided character (codeword) and its frequency
struct MinHeapNode* newHeapNode(char codeword, unsigned freq)

struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode));

temp->left = temp->right = NULL;
temp->codeword = codeword;
temp->freq = freq;

return temp;


// Creating a new dynamically allocated min heap with given capacity
struct MinHeap* createMinHeap(unsigned capacity)

struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap));
minHeap->size = 0; // Setting the size to 0
minHeap->capacity = capacity; // Inserting the given capacity
// Inserting into the heap node pointers array
minHeap->array= (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode*));
return minHeap;


// Swap function to swap two min heap nodes
void swap(struct MinHeapNode** a, struct MinHeapNode** b)

struct MinHeapNode* temp2 = *a;
*a = *b;
*b = temp2;

// minHeapify function
void minHeapify(struct MinHeap* minHeap, int index)

int smallest = index;
int leftSon = 2 * index + 1;
int rightSon = 2 * index + 2;

if (leftSon < minHeap->size && minHeap->array[leftSon]->freq < minHeap->array[smallest]->freq)
smallest = leftSon;

if (rightSon < minHeap->size && minHeap->array[rightSon]-> freq < minHeap->array[smallest]->freq)
smallest = rightSon;

if (smallest != index)

swap(&minHeap->array[smallest], &minHeap->array[index]);
minHeapify(minHeap, smallest);



// Checking if the size of the heap is 1
int heapSizeOne(struct MinHeap* minHeap)

return (minHeap->size == 1);


// Extracting minimum value node from the heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap)

struct MinHeapNode* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
--minHeap->size;
minHeapify(minHeap, 0);
return temp;


// Inserting a new node into min heap
void insert(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode)

++minHeap->size;
int i = minHeap->size - 1;
while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq)

minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;

minHeap->array[i] = minHeapNode;


// Build function to build min heap
void build(struct MinHeap* minHeap)

int n = minHeap->size - 1;
for (int i = (n - 1) / 2; i >= 0; --i)
minHeapify(minHeap, i);


// Display function to print an array
void display(int arr[], int n)

int i;
for (i = 0; i < n; ++i)
cout << arr[i];
cout << "n";


// Function to check if the node is a leaf
int isLeaf(struct MinHeapNode* root)

return !(root->left) && !(root->right);



// Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency.
struct MinHeap* create(char codeword[], int freq[], int size)

struct MinHeap* minHeap = createMinHeap(size);
for (int i = 0; i < size; ++i)
minHeap->array[i] = newHeapNode(codeword[i], freq[i]);
minHeap->size = size;
build(minHeap);
return minHeap;


// Function that builds the Huffman tree
struct MinHeapNode* buildHT(char codeword[], int freq[], int size)

struct MinHeapNode *left, *right, *top;

// Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency.
struct MinHeap* minHeap = create(codeword, freq, size);

// while loop runs as long as the size of heap doesn't reach 1
while (!heapSizeOne(minHeap))

// Getting the two minimums from min heap
left = extractMin(minHeap);
right = extractMin(minHeap);

// The frequency of top is computed as the sum of the frequencies of left and right nodes.
top = newHeapNode('_', left->freq + right->freq);
top->left = left;
top->right = right;
insert(minHeap, top);

// The remaining value is the root node which completes the tree
return extractMin(minHeap);


// Prints huffman codes from the root of
// Displaying Huffman codes
void displayHC(struct MinHeapNode* root, int arr[], int top)


// Left side is given the value 0
if (root->left)

arr[top] = 0;
displayHC(root->left, arr, top + 1);

// Right side is given the value 1
if (root->right)

arr[top] = 1;
displayHC(root->right, arr, top + 1);

// If this is a leaf node, print the character and its code.
if (isLeaf(root))

cout << root->codeword << ": ";
display(arr, top);



// Building a Huffman Tree and displaying the codes
void HuffmanCodes(char codeword[], int freq[], int size)


// Building a HT
struct MinHeapNode* root = buildHT(codeword, freq, size);

// Displaying the HT we built
int arr[MAX_TREE_HEIGHT], top = 0;

displayHC(root, arr, top);


// I used the example from the PP presentation in the Files section - The Hoffman Coding
int main()
4t B






c++ homework compression heap






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 5 at 10:13









200_success

132k20159426




132k20159426










asked May 5 at 7:25









Stevan MilicStevan Milic

927




927







  • 16




    $begingroup$
    Your code is pretty much "C with cout and using namespace std;s". It doesn't look like C++ at all.
    $endgroup$
    – L. F.
    May 5 at 10:36






  • 6




    $begingroup$
    Is this code for an assignment? I'd recommend not putting it online if you haven't yet had it graded.
    $endgroup$
    – TEK
    May 5 at 10:40







  • 10




    $begingroup$
    You seem to make the same mistakes over and over again. Could I suggest you consider using some of the answers you are receiving.
    $endgroup$
    – bruglesco
    May 5 at 20:19










  • $begingroup$
    It looks like you have two different things going on here: A min heap data structure, and an implementation of a huffman code algorithm that happens to use a min heap. Don't conflate the two. Build a generic min heap (that'll come in useful in other places), and build a separate huffman code function that uses it.
    $endgroup$
    – Alexander
    May 6 at 2:32










  • $begingroup$
    Which version of C++ are you using? (command line parameters or compiler version would be useful )
    $endgroup$
    – Robert Andrzejuk
    May 6 at 8:17













  • 16




    $begingroup$
    Your code is pretty much "C with cout and using namespace std;s". It doesn't look like C++ at all.
    $endgroup$
    – L. F.
    May 5 at 10:36






  • 6




    $begingroup$
    Is this code for an assignment? I'd recommend not putting it online if you haven't yet had it graded.
    $endgroup$
    – TEK
    May 5 at 10:40







  • 10




    $begingroup$
    You seem to make the same mistakes over and over again. Could I suggest you consider using some of the answers you are receiving.
    $endgroup$
    – bruglesco
    May 5 at 20:19










  • $begingroup$
    It looks like you have two different things going on here: A min heap data structure, and an implementation of a huffman code algorithm that happens to use a min heap. Don't conflate the two. Build a generic min heap (that'll come in useful in other places), and build a separate huffman code function that uses it.
    $endgroup$
    – Alexander
    May 6 at 2:32










  • $begingroup$
    Which version of C++ are you using? (command line parameters or compiler version would be useful )
    $endgroup$
    – Robert Andrzejuk
    May 6 at 8:17








16




16




$begingroup$
Your code is pretty much "C with cout and using namespace std;s". It doesn't look like C++ at all.
$endgroup$
– L. F.
May 5 at 10:36




$begingroup$
Your code is pretty much "C with cout and using namespace std;s". It doesn't look like C++ at all.
$endgroup$
– L. F.
May 5 at 10:36




6




6




$begingroup$
Is this code for an assignment? I'd recommend not putting it online if you haven't yet had it graded.
$endgroup$
– TEK
May 5 at 10:40





$begingroup$
Is this code for an assignment? I'd recommend not putting it online if you haven't yet had it graded.
$endgroup$
– TEK
May 5 at 10:40





10




10




$begingroup$
You seem to make the same mistakes over and over again. Could I suggest you consider using some of the answers you are receiving.
$endgroup$
– bruglesco
May 5 at 20:19




$begingroup$
You seem to make the same mistakes over and over again. Could I suggest you consider using some of the answers you are receiving.
$endgroup$
– bruglesco
May 5 at 20:19












$begingroup$
It looks like you have two different things going on here: A min heap data structure, and an implementation of a huffman code algorithm that happens to use a min heap. Don't conflate the two. Build a generic min heap (that'll come in useful in other places), and build a separate huffman code function that uses it.
$endgroup$
– Alexander
May 6 at 2:32




$begingroup$
It looks like you have two different things going on here: A min heap data structure, and an implementation of a huffman code algorithm that happens to use a min heap. Don't conflate the two. Build a generic min heap (that'll come in useful in other places), and build a separate huffman code function that uses it.
$endgroup$
– Alexander
May 6 at 2:32












$begingroup$
Which version of C++ are you using? (command line parameters or compiler version would be useful )
$endgroup$
– Robert Andrzejuk
May 6 at 8:17





$begingroup$
Which version of C++ are you using? (command line parameters or compiler version would be useful )
$endgroup$
– Robert Andrzejuk
May 6 at 8:17











3 Answers
3






active

oldest

votes


















14












$begingroup$

Looks pretty readable and I agree with most of your formatting however there are some things that stand out.



  • using namespace std;
    Kick this habit before it kicks you.


  • #define MAX_TREE_HEIGHT 1000

    I'd prefer to put this into an anonymous namespace as implementation detail


  • unsigned freq;

    Not everyone knows this defaults to int. Might be a good idea to add int for readability


  • At a glance this seems to leak memory

    Confirm with valgrind. You're using malloc but no free. Better use new/delete, even better use smart pointers and friends.


  • Braces (highly subjective)

    Many people disagree on this one but I prefer to always include braces where possible


  • Prefer using n over std::endl


  • system("pause"); should be avoided


  • If you don't depend on return values you can omit return 0 from main (subjective)


Overall this seems very C-ish, not so much like (modern) C++. Are you perhaps prohibited from using certain language features?






share|improve this answer









$endgroup$








  • 8




    $begingroup$
    1. It doesn't matter if the #define is in a namespace, as it doesn't respect them anyway. 2. Nobody who needs unsigned int spelled out can legitimately claim even passing familiarity with C++, so they should not be the target audience. 3. return 0; can always be omitted from main(), but nowhere else.
    $endgroup$
    – Deduplicator
    May 5 at 9:02






  • 9




    $begingroup$
    "Not everyone knows this defaults to int." - People not knowing that should not touch others code anyway.
    $endgroup$
    – Broman
    May 5 at 10:15










  • $begingroup$
    you complain it looks to "C-ish" but also that he uses the correct std::endl over the very C-ish n. Make up your mind :)
    $endgroup$
    – jwenting
    May 6 at 11:23







  • 3




    $begingroup$
    @jwenting How is the character n related to C at all? How is std::endl correct when it has side-effects which are not desirable here?
    $endgroup$
    – Vincent Savard
    May 6 at 12:57










  • $begingroup$
    @yuri Thank you very much for your answer, I tried to correct the mistakes you wrote but somehow I still get the wrong output. It seems like I have a logic error in my code and I can't figure it out.
    $endgroup$
    – Stevan Milic
    May 8 at 4:27


















8












$begingroup$

  • NEVER use using namespace std. It can cause hard tracked bugs. Read here why: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice


  • The code has WAY to much comments. "Well commented" does not mean that it should have tons of comments. I have seen well commented code without comments. A problem with comments is that you need to maintain them. Will you remember to change comments when you change the code? Probably not. An example of a completely useless comment is minHeap->size = 0; // Setting the size to 0. You have a variable called size and you're assigning it to the value 0. There's no need for a comment there.


  • If you're coding C++, then code C++. No reason to use malloc in C++, because this language has far easier and secure methods for allocating memory.






share|improve this answer











$endgroup$












  • $begingroup$
    On the other hand, minHeap->size = 0; // make heap empty is a comment that might be useful
    $endgroup$
    – Hagen von Eitzen
    May 5 at 17:02










  • $begingroup$
    @HagenvonEitzen I disagree. Sure, it gives a little information, but it's not worth it. It's just noise. When I am about to write a comment, I always think if I instead can rewrite the code so that the comment is not necessary.
    $endgroup$
    – Broman
    May 5 at 17:07


















5












$begingroup$

Prefer Constants Over Macros

The line



#define MAX_TREE_HEIGHT 1000


might be better written as



const size_t MAX_TREE_HEIGHT = 1000;


In C++ constants are preferred over macros because constants are type safe and provide more error checking at compile time.



Prefer new Type(); Over malloc()

The C++ programming language allowed malloc(), calloc() and free() for backwards comparability with the C programming language, however, it also introduced new Type() and delete(). Generally new and delete are preferred over the older C language functions. Using new has these benefits:



  • new is an operator, malloc is a function

  • new returns the proper type so the cast is not necessary

  • new executes constructors to properly initialize the new object, the use of malloc requires additional code to initialize the new object.

  • new automatically performs the error checking for failed memory allocation and throws an exception if the allocation failed. For malloc additional code needs to be added to make sure malloc did not return NULL (or nullptr in the case of C++).

  • new knows the amount of memory to allocate for the object, malloc requires the programmer to specify the size of the object.

References about new versus malloc can be found here, here and this stackoverflow question.



When allocating arrays in C calloc() is preferred over malloc() for two reasons, first it is clear that an array is being allocated because there are two arguments, one is the size of the array and the other is the size of the object. The second reason is that calloc() clears the memory of the objects (initializes the entire array contents to zero), malloc() requires the programmer to clear the contents of the array.



Namespaces

Namespaces were added to the definition of the C++ language to prevent collisions of function names and variables. Operators such as cin and cout can be overloaded to display the contents of objects. In this case the overloaded NAMESPACE::cout may include references to std::cout. Generally using namespace std; is considered a bad programming practice because it can cause function name or variable name collisions. For maintainability reasons never put using namespace std; into a header file.



Use Container Classes When Possible

The array allocated by this line



 struct MinHeap* minHeap = createMinHeap(size);


might be better as the C++ container class std::vector or even std::vector (does the code really need the pointers).



std::vector is a variable sized array of any type, it grows as needed.






share|improve this answer











$endgroup$












  • $begingroup$
    new is not normally faster than malloc. Do you have an implementation where it is?
    $endgroup$
    – Anonymous
    May 5 at 20:47










  • $begingroup$
    @Anonymous techdifferences.com/difference-between-new-and-malloc.html see execution.
    $endgroup$
    – pacmaninbw
    May 5 at 20:55










  • $begingroup$
    That source says "The new operator cuts off the execution time as it is an operator, not a function", which is confused — are they thinking it saves function call overhead or something? In reality, new is usually either exactly as fast as malloc (if it compiles to a malloc call) or slightly slower (if it adds an extra wrapper).
    $endgroup$
    – Anonymous
    May 5 at 21:03










  • $begingroup$
    @Anonymous I've removed it from the answer.
    $endgroup$
    – pacmaninbw
    May 5 at 21:05











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f219738%2fhuffman-code-in-c%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









14












$begingroup$

Looks pretty readable and I agree with most of your formatting however there are some things that stand out.



  • using namespace std;
    Kick this habit before it kicks you.


  • #define MAX_TREE_HEIGHT 1000

    I'd prefer to put this into an anonymous namespace as implementation detail


  • unsigned freq;

    Not everyone knows this defaults to int. Might be a good idea to add int for readability


  • At a glance this seems to leak memory

    Confirm with valgrind. You're using malloc but no free. Better use new/delete, even better use smart pointers and friends.


  • Braces (highly subjective)

    Many people disagree on this one but I prefer to always include braces where possible


  • Prefer using n over std::endl


  • system("pause"); should be avoided


  • If you don't depend on return values you can omit return 0 from main (subjective)


Overall this seems very C-ish, not so much like (modern) C++. Are you perhaps prohibited from using certain language features?






share|improve this answer









$endgroup$








  • 8




    $begingroup$
    1. It doesn't matter if the #define is in a namespace, as it doesn't respect them anyway. 2. Nobody who needs unsigned int spelled out can legitimately claim even passing familiarity with C++, so they should not be the target audience. 3. return 0; can always be omitted from main(), but nowhere else.
    $endgroup$
    – Deduplicator
    May 5 at 9:02






  • 9




    $begingroup$
    "Not everyone knows this defaults to int." - People not knowing that should not touch others code anyway.
    $endgroup$
    – Broman
    May 5 at 10:15










  • $begingroup$
    you complain it looks to "C-ish" but also that he uses the correct std::endl over the very C-ish n. Make up your mind :)
    $endgroup$
    – jwenting
    May 6 at 11:23







  • 3




    $begingroup$
    @jwenting How is the character n related to C at all? How is std::endl correct when it has side-effects which are not desirable here?
    $endgroup$
    – Vincent Savard
    May 6 at 12:57










  • $begingroup$
    @yuri Thank you very much for your answer, I tried to correct the mistakes you wrote but somehow I still get the wrong output. It seems like I have a logic error in my code and I can't figure it out.
    $endgroup$
    – Stevan Milic
    May 8 at 4:27















14












$begingroup$

Looks pretty readable and I agree with most of your formatting however there are some things that stand out.



  • using namespace std;
    Kick this habit before it kicks you.


  • #define MAX_TREE_HEIGHT 1000

    I'd prefer to put this into an anonymous namespace as implementation detail


  • unsigned freq;

    Not everyone knows this defaults to int. Might be a good idea to add int for readability


  • At a glance this seems to leak memory

    Confirm with valgrind. You're using malloc but no free. Better use new/delete, even better use smart pointers and friends.


  • Braces (highly subjective)

    Many people disagree on this one but I prefer to always include braces where possible


  • Prefer using n over std::endl


  • system("pause"); should be avoided


  • If you don't depend on return values you can omit return 0 from main (subjective)


Overall this seems very C-ish, not so much like (modern) C++. Are you perhaps prohibited from using certain language features?






share|improve this answer









$endgroup$








  • 8




    $begingroup$
    1. It doesn't matter if the #define is in a namespace, as it doesn't respect them anyway. 2. Nobody who needs unsigned int spelled out can legitimately claim even passing familiarity with C++, so they should not be the target audience. 3. return 0; can always be omitted from main(), but nowhere else.
    $endgroup$
    – Deduplicator
    May 5 at 9:02






  • 9




    $begingroup$
    "Not everyone knows this defaults to int." - People not knowing that should not touch others code anyway.
    $endgroup$
    – Broman
    May 5 at 10:15










  • $begingroup$
    you complain it looks to "C-ish" but also that he uses the correct std::endl over the very C-ish n. Make up your mind :)
    $endgroup$
    – jwenting
    May 6 at 11:23







  • 3




    $begingroup$
    @jwenting How is the character n related to C at all? How is std::endl correct when it has side-effects which are not desirable here?
    $endgroup$
    – Vincent Savard
    May 6 at 12:57










  • $begingroup$
    @yuri Thank you very much for your answer, I tried to correct the mistakes you wrote but somehow I still get the wrong output. It seems like I have a logic error in my code and I can't figure it out.
    $endgroup$
    – Stevan Milic
    May 8 at 4:27













14












14








14





$begingroup$

Looks pretty readable and I agree with most of your formatting however there are some things that stand out.



  • using namespace std;
    Kick this habit before it kicks you.


  • #define MAX_TREE_HEIGHT 1000

    I'd prefer to put this into an anonymous namespace as implementation detail


  • unsigned freq;

    Not everyone knows this defaults to int. Might be a good idea to add int for readability


  • At a glance this seems to leak memory

    Confirm with valgrind. You're using malloc but no free. Better use new/delete, even better use smart pointers and friends.


  • Braces (highly subjective)

    Many people disagree on this one but I prefer to always include braces where possible


  • Prefer using n over std::endl


  • system("pause"); should be avoided


  • If you don't depend on return values you can omit return 0 from main (subjective)


Overall this seems very C-ish, not so much like (modern) C++. Are you perhaps prohibited from using certain language features?






share|improve this answer









$endgroup$



Looks pretty readable and I agree with most of your formatting however there are some things that stand out.



  • using namespace std;
    Kick this habit before it kicks you.


  • #define MAX_TREE_HEIGHT 1000

    I'd prefer to put this into an anonymous namespace as implementation detail


  • unsigned freq;

    Not everyone knows this defaults to int. Might be a good idea to add int for readability


  • At a glance this seems to leak memory

    Confirm with valgrind. You're using malloc but no free. Better use new/delete, even better use smart pointers and friends.


  • Braces (highly subjective)

    Many people disagree on this one but I prefer to always include braces where possible


  • Prefer using n over std::endl


  • system("pause"); should be avoided


  • If you don't depend on return values you can omit return 0 from main (subjective)


Overall this seems very C-ish, not so much like (modern) C++. Are you perhaps prohibited from using certain language features?







share|improve this answer












share|improve this answer



share|improve this answer










answered May 5 at 8:55









yuriyuri

3,87721135




3,87721135







  • 8




    $begingroup$
    1. It doesn't matter if the #define is in a namespace, as it doesn't respect them anyway. 2. Nobody who needs unsigned int spelled out can legitimately claim even passing familiarity with C++, so they should not be the target audience. 3. return 0; can always be omitted from main(), but nowhere else.
    $endgroup$
    – Deduplicator
    May 5 at 9:02






  • 9




    $begingroup$
    "Not everyone knows this defaults to int." - People not knowing that should not touch others code anyway.
    $endgroup$
    – Broman
    May 5 at 10:15










  • $begingroup$
    you complain it looks to "C-ish" but also that he uses the correct std::endl over the very C-ish n. Make up your mind :)
    $endgroup$
    – jwenting
    May 6 at 11:23







  • 3




    $begingroup$
    @jwenting How is the character n related to C at all? How is std::endl correct when it has side-effects which are not desirable here?
    $endgroup$
    – Vincent Savard
    May 6 at 12:57










  • $begingroup$
    @yuri Thank you very much for your answer, I tried to correct the mistakes you wrote but somehow I still get the wrong output. It seems like I have a logic error in my code and I can't figure it out.
    $endgroup$
    – Stevan Milic
    May 8 at 4:27












  • 8




    $begingroup$
    1. It doesn't matter if the #define is in a namespace, as it doesn't respect them anyway. 2. Nobody who needs unsigned int spelled out can legitimately claim even passing familiarity with C++, so they should not be the target audience. 3. return 0; can always be omitted from main(), but nowhere else.
    $endgroup$
    – Deduplicator
    May 5 at 9:02






  • 9




    $begingroup$
    "Not everyone knows this defaults to int." - People not knowing that should not touch others code anyway.
    $endgroup$
    – Broman
    May 5 at 10:15










  • $begingroup$
    you complain it looks to "C-ish" but also that he uses the correct std::endl over the very C-ish n. Make up your mind :)
    $endgroup$
    – jwenting
    May 6 at 11:23







  • 3




    $begingroup$
    @jwenting How is the character n related to C at all? How is std::endl correct when it has side-effects which are not desirable here?
    $endgroup$
    – Vincent Savard
    May 6 at 12:57










  • $begingroup$
    @yuri Thank you very much for your answer, I tried to correct the mistakes you wrote but somehow I still get the wrong output. It seems like I have a logic error in my code and I can't figure it out.
    $endgroup$
    – Stevan Milic
    May 8 at 4:27







8




8




$begingroup$
1. It doesn't matter if the #define is in a namespace, as it doesn't respect them anyway. 2. Nobody who needs unsigned int spelled out can legitimately claim even passing familiarity with C++, so they should not be the target audience. 3. return 0; can always be omitted from main(), but nowhere else.
$endgroup$
– Deduplicator
May 5 at 9:02




$begingroup$
1. It doesn't matter if the #define is in a namespace, as it doesn't respect them anyway. 2. Nobody who needs unsigned int spelled out can legitimately claim even passing familiarity with C++, so they should not be the target audience. 3. return 0; can always be omitted from main(), but nowhere else.
$endgroup$
– Deduplicator
May 5 at 9:02




9




9




$begingroup$
"Not everyone knows this defaults to int." - People not knowing that should not touch others code anyway.
$endgroup$
– Broman
May 5 at 10:15




$begingroup$
"Not everyone knows this defaults to int." - People not knowing that should not touch others code anyway.
$endgroup$
– Broman
May 5 at 10:15












$begingroup$
you complain it looks to "C-ish" but also that he uses the correct std::endl over the very C-ish n. Make up your mind :)
$endgroup$
– jwenting
May 6 at 11:23





$begingroup$
you complain it looks to "C-ish" but also that he uses the correct std::endl over the very C-ish n. Make up your mind :)
$endgroup$
– jwenting
May 6 at 11:23





3




3




$begingroup$
@jwenting How is the character n related to C at all? How is std::endl correct when it has side-effects which are not desirable here?
$endgroup$
– Vincent Savard
May 6 at 12:57




$begingroup$
@jwenting How is the character n related to C at all? How is std::endl correct when it has side-effects which are not desirable here?
$endgroup$
– Vincent Savard
May 6 at 12:57












$begingroup$
@yuri Thank you very much for your answer, I tried to correct the mistakes you wrote but somehow I still get the wrong output. It seems like I have a logic error in my code and I can't figure it out.
$endgroup$
– Stevan Milic
May 8 at 4:27




$begingroup$
@yuri Thank you very much for your answer, I tried to correct the mistakes you wrote but somehow I still get the wrong output. It seems like I have a logic error in my code and I can't figure it out.
$endgroup$
– Stevan Milic
May 8 at 4:27













8












$begingroup$

  • NEVER use using namespace std. It can cause hard tracked bugs. Read here why: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice


  • The code has WAY to much comments. "Well commented" does not mean that it should have tons of comments. I have seen well commented code without comments. A problem with comments is that you need to maintain them. Will you remember to change comments when you change the code? Probably not. An example of a completely useless comment is minHeap->size = 0; // Setting the size to 0. You have a variable called size and you're assigning it to the value 0. There's no need for a comment there.


  • If you're coding C++, then code C++. No reason to use malloc in C++, because this language has far easier and secure methods for allocating memory.






share|improve this answer











$endgroup$












  • $begingroup$
    On the other hand, minHeap->size = 0; // make heap empty is a comment that might be useful
    $endgroup$
    – Hagen von Eitzen
    May 5 at 17:02










  • $begingroup$
    @HagenvonEitzen I disagree. Sure, it gives a little information, but it's not worth it. It's just noise. When I am about to write a comment, I always think if I instead can rewrite the code so that the comment is not necessary.
    $endgroup$
    – Broman
    May 5 at 17:07















8












$begingroup$

  • NEVER use using namespace std. It can cause hard tracked bugs. Read here why: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice


  • The code has WAY to much comments. "Well commented" does not mean that it should have tons of comments. I have seen well commented code without comments. A problem with comments is that you need to maintain them. Will you remember to change comments when you change the code? Probably not. An example of a completely useless comment is minHeap->size = 0; // Setting the size to 0. You have a variable called size and you're assigning it to the value 0. There's no need for a comment there.


  • If you're coding C++, then code C++. No reason to use malloc in C++, because this language has far easier and secure methods for allocating memory.






share|improve this answer











$endgroup$












  • $begingroup$
    On the other hand, minHeap->size = 0; // make heap empty is a comment that might be useful
    $endgroup$
    – Hagen von Eitzen
    May 5 at 17:02










  • $begingroup$
    @HagenvonEitzen I disagree. Sure, it gives a little information, but it's not worth it. It's just noise. When I am about to write a comment, I always think if I instead can rewrite the code so that the comment is not necessary.
    $endgroup$
    – Broman
    May 5 at 17:07













8












8








8





$begingroup$

  • NEVER use using namespace std. It can cause hard tracked bugs. Read here why: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice


  • The code has WAY to much comments. "Well commented" does not mean that it should have tons of comments. I have seen well commented code without comments. A problem with comments is that you need to maintain them. Will you remember to change comments when you change the code? Probably not. An example of a completely useless comment is minHeap->size = 0; // Setting the size to 0. You have a variable called size and you're assigning it to the value 0. There's no need for a comment there.


  • If you're coding C++, then code C++. No reason to use malloc in C++, because this language has far easier and secure methods for allocating memory.






share|improve this answer











$endgroup$



  • NEVER use using namespace std. It can cause hard tracked bugs. Read here why: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice


  • The code has WAY to much comments. "Well commented" does not mean that it should have tons of comments. I have seen well commented code without comments. A problem with comments is that you need to maintain them. Will you remember to change comments when you change the code? Probably not. An example of a completely useless comment is minHeap->size = 0; // Setting the size to 0. You have a variable called size and you're assigning it to the value 0. There's no need for a comment there.


  • If you're coding C++, then code C++. No reason to use malloc in C++, because this language has far easier and secure methods for allocating memory.







share|improve this answer














share|improve this answer



share|improve this answer








edited May 5 at 11:43

























answered May 5 at 10:26









BromanBroman

499210




499210











  • $begingroup$
    On the other hand, minHeap->size = 0; // make heap empty is a comment that might be useful
    $endgroup$
    – Hagen von Eitzen
    May 5 at 17:02










  • $begingroup$
    @HagenvonEitzen I disagree. Sure, it gives a little information, but it's not worth it. It's just noise. When I am about to write a comment, I always think if I instead can rewrite the code so that the comment is not necessary.
    $endgroup$
    – Broman
    May 5 at 17:07
















  • $begingroup$
    On the other hand, minHeap->size = 0; // make heap empty is a comment that might be useful
    $endgroup$
    – Hagen von Eitzen
    May 5 at 17:02










  • $begingroup$
    @HagenvonEitzen I disagree. Sure, it gives a little information, but it's not worth it. It's just noise. When I am about to write a comment, I always think if I instead can rewrite the code so that the comment is not necessary.
    $endgroup$
    – Broman
    May 5 at 17:07















$begingroup$
On the other hand, minHeap->size = 0; // make heap empty is a comment that might be useful
$endgroup$
– Hagen von Eitzen
May 5 at 17:02




$begingroup$
On the other hand, minHeap->size = 0; // make heap empty is a comment that might be useful
$endgroup$
– Hagen von Eitzen
May 5 at 17:02












$begingroup$
@HagenvonEitzen I disagree. Sure, it gives a little information, but it's not worth it. It's just noise. When I am about to write a comment, I always think if I instead can rewrite the code so that the comment is not necessary.
$endgroup$
– Broman
May 5 at 17:07




$begingroup$
@HagenvonEitzen I disagree. Sure, it gives a little information, but it's not worth it. It's just noise. When I am about to write a comment, I always think if I instead can rewrite the code so that the comment is not necessary.
$endgroup$
– Broman
May 5 at 17:07











5












$begingroup$

Prefer Constants Over Macros

The line



#define MAX_TREE_HEIGHT 1000


might be better written as



const size_t MAX_TREE_HEIGHT = 1000;


In C++ constants are preferred over macros because constants are type safe and provide more error checking at compile time.



Prefer new Type(); Over malloc()

The C++ programming language allowed malloc(), calloc() and free() for backwards comparability with the C programming language, however, it also introduced new Type() and delete(). Generally new and delete are preferred over the older C language functions. Using new has these benefits:



  • new is an operator, malloc is a function

  • new returns the proper type so the cast is not necessary

  • new executes constructors to properly initialize the new object, the use of malloc requires additional code to initialize the new object.

  • new automatically performs the error checking for failed memory allocation and throws an exception if the allocation failed. For malloc additional code needs to be added to make sure malloc did not return NULL (or nullptr in the case of C++).

  • new knows the amount of memory to allocate for the object, malloc requires the programmer to specify the size of the object.

References about new versus malloc can be found here, here and this stackoverflow question.



When allocating arrays in C calloc() is preferred over malloc() for two reasons, first it is clear that an array is being allocated because there are two arguments, one is the size of the array and the other is the size of the object. The second reason is that calloc() clears the memory of the objects (initializes the entire array contents to zero), malloc() requires the programmer to clear the contents of the array.



Namespaces

Namespaces were added to the definition of the C++ language to prevent collisions of function names and variables. Operators such as cin and cout can be overloaded to display the contents of objects. In this case the overloaded NAMESPACE::cout may include references to std::cout. Generally using namespace std; is considered a bad programming practice because it can cause function name or variable name collisions. For maintainability reasons never put using namespace std; into a header file.



Use Container Classes When Possible

The array allocated by this line



 struct MinHeap* minHeap = createMinHeap(size);


might be better as the C++ container class std::vector or even std::vector (does the code really need the pointers).



std::vector is a variable sized array of any type, it grows as needed.






share|improve this answer











$endgroup$












  • $begingroup$
    new is not normally faster than malloc. Do you have an implementation where it is?
    $endgroup$
    – Anonymous
    May 5 at 20:47










  • $begingroup$
    @Anonymous techdifferences.com/difference-between-new-and-malloc.html see execution.
    $endgroup$
    – pacmaninbw
    May 5 at 20:55










  • $begingroup$
    That source says "The new operator cuts off the execution time as it is an operator, not a function", which is confused — are they thinking it saves function call overhead or something? In reality, new is usually either exactly as fast as malloc (if it compiles to a malloc call) or slightly slower (if it adds an extra wrapper).
    $endgroup$
    – Anonymous
    May 5 at 21:03










  • $begingroup$
    @Anonymous I've removed it from the answer.
    $endgroup$
    – pacmaninbw
    May 5 at 21:05















5












$begingroup$

Prefer Constants Over Macros

The line



#define MAX_TREE_HEIGHT 1000


might be better written as



const size_t MAX_TREE_HEIGHT = 1000;


In C++ constants are preferred over macros because constants are type safe and provide more error checking at compile time.



Prefer new Type(); Over malloc()

The C++ programming language allowed malloc(), calloc() and free() for backwards comparability with the C programming language, however, it also introduced new Type() and delete(). Generally new and delete are preferred over the older C language functions. Using new has these benefits:



  • new is an operator, malloc is a function

  • new returns the proper type so the cast is not necessary

  • new executes constructors to properly initialize the new object, the use of malloc requires additional code to initialize the new object.

  • new automatically performs the error checking for failed memory allocation and throws an exception if the allocation failed. For malloc additional code needs to be added to make sure malloc did not return NULL (or nullptr in the case of C++).

  • new knows the amount of memory to allocate for the object, malloc requires the programmer to specify the size of the object.

References about new versus malloc can be found here, here and this stackoverflow question.



When allocating arrays in C calloc() is preferred over malloc() for two reasons, first it is clear that an array is being allocated because there are two arguments, one is the size of the array and the other is the size of the object. The second reason is that calloc() clears the memory of the objects (initializes the entire array contents to zero), malloc() requires the programmer to clear the contents of the array.



Namespaces

Namespaces were added to the definition of the C++ language to prevent collisions of function names and variables. Operators such as cin and cout can be overloaded to display the contents of objects. In this case the overloaded NAMESPACE::cout may include references to std::cout. Generally using namespace std; is considered a bad programming practice because it can cause function name or variable name collisions. For maintainability reasons never put using namespace std; into a header file.



Use Container Classes When Possible

The array allocated by this line



 struct MinHeap* minHeap = createMinHeap(size);


might be better as the C++ container class std::vector or even std::vector (does the code really need the pointers).



std::vector is a variable sized array of any type, it grows as needed.






share|improve this answer











$endgroup$












  • $begingroup$
    new is not normally faster than malloc. Do you have an implementation where it is?
    $endgroup$
    – Anonymous
    May 5 at 20:47










  • $begingroup$
    @Anonymous techdifferences.com/difference-between-new-and-malloc.html see execution.
    $endgroup$
    – pacmaninbw
    May 5 at 20:55










  • $begingroup$
    That source says "The new operator cuts off the execution time as it is an operator, not a function", which is confused — are they thinking it saves function call overhead or something? In reality, new is usually either exactly as fast as malloc (if it compiles to a malloc call) or slightly slower (if it adds an extra wrapper).
    $endgroup$
    – Anonymous
    May 5 at 21:03










  • $begingroup$
    @Anonymous I've removed it from the answer.
    $endgroup$
    – pacmaninbw
    May 5 at 21:05













5












5








5





$begingroup$

Prefer Constants Over Macros

The line



#define MAX_TREE_HEIGHT 1000


might be better written as



const size_t MAX_TREE_HEIGHT = 1000;


In C++ constants are preferred over macros because constants are type safe and provide more error checking at compile time.



Prefer new Type(); Over malloc()

The C++ programming language allowed malloc(), calloc() and free() for backwards comparability with the C programming language, however, it also introduced new Type() and delete(). Generally new and delete are preferred over the older C language functions. Using new has these benefits:



  • new is an operator, malloc is a function

  • new returns the proper type so the cast is not necessary

  • new executes constructors to properly initialize the new object, the use of malloc requires additional code to initialize the new object.

  • new automatically performs the error checking for failed memory allocation and throws an exception if the allocation failed. For malloc additional code needs to be added to make sure malloc did not return NULL (or nullptr in the case of C++).

  • new knows the amount of memory to allocate for the object, malloc requires the programmer to specify the size of the object.

References about new versus malloc can be found here, here and this stackoverflow question.



When allocating arrays in C calloc() is preferred over malloc() for two reasons, first it is clear that an array is being allocated because there are two arguments, one is the size of the array and the other is the size of the object. The second reason is that calloc() clears the memory of the objects (initializes the entire array contents to zero), malloc() requires the programmer to clear the contents of the array.



Namespaces

Namespaces were added to the definition of the C++ language to prevent collisions of function names and variables. Operators such as cin and cout can be overloaded to display the contents of objects. In this case the overloaded NAMESPACE::cout may include references to std::cout. Generally using namespace std; is considered a bad programming practice because it can cause function name or variable name collisions. For maintainability reasons never put using namespace std; into a header file.



Use Container Classes When Possible

The array allocated by this line



 struct MinHeap* minHeap = createMinHeap(size);


might be better as the C++ container class std::vector or even std::vector (does the code really need the pointers).



std::vector is a variable sized array of any type, it grows as needed.






share|improve this answer











$endgroup$



Prefer Constants Over Macros

The line



#define MAX_TREE_HEIGHT 1000


might be better written as



const size_t MAX_TREE_HEIGHT = 1000;


In C++ constants are preferred over macros because constants are type safe and provide more error checking at compile time.



Prefer new Type(); Over malloc()

The C++ programming language allowed malloc(), calloc() and free() for backwards comparability with the C programming language, however, it also introduced new Type() and delete(). Generally new and delete are preferred over the older C language functions. Using new has these benefits:



  • new is an operator, malloc is a function

  • new returns the proper type so the cast is not necessary

  • new executes constructors to properly initialize the new object, the use of malloc requires additional code to initialize the new object.

  • new automatically performs the error checking for failed memory allocation and throws an exception if the allocation failed. For malloc additional code needs to be added to make sure malloc did not return NULL (or nullptr in the case of C++).

  • new knows the amount of memory to allocate for the object, malloc requires the programmer to specify the size of the object.

References about new versus malloc can be found here, here and this stackoverflow question.



When allocating arrays in C calloc() is preferred over malloc() for two reasons, first it is clear that an array is being allocated because there are two arguments, one is the size of the array and the other is the size of the object. The second reason is that calloc() clears the memory of the objects (initializes the entire array contents to zero), malloc() requires the programmer to clear the contents of the array.



Namespaces

Namespaces were added to the definition of the C++ language to prevent collisions of function names and variables. Operators such as cin and cout can be overloaded to display the contents of objects. In this case the overloaded NAMESPACE::cout may include references to std::cout. Generally using namespace std; is considered a bad programming practice because it can cause function name or variable name collisions. For maintainability reasons never put using namespace std; into a header file.



Use Container Classes When Possible

The array allocated by this line



 struct MinHeap* minHeap = createMinHeap(size);


might be better as the C++ container class std::vector or even std::vector (does the code really need the pointers).



std::vector is a variable sized array of any type, it grows as needed.







share|improve this answer














share|improve this answer



share|improve this answer








edited May 5 at 20:57

























answered May 5 at 16:00









pacmaninbwpacmaninbw

6,36421639




6,36421639











  • $begingroup$
    new is not normally faster than malloc. Do you have an implementation where it is?
    $endgroup$
    – Anonymous
    May 5 at 20:47










  • $begingroup$
    @Anonymous techdifferences.com/difference-between-new-and-malloc.html see execution.
    $endgroup$
    – pacmaninbw
    May 5 at 20:55










  • $begingroup$
    That source says "The new operator cuts off the execution time as it is an operator, not a function", which is confused — are they thinking it saves function call overhead or something? In reality, new is usually either exactly as fast as malloc (if it compiles to a malloc call) or slightly slower (if it adds an extra wrapper).
    $endgroup$
    – Anonymous
    May 5 at 21:03










  • $begingroup$
    @Anonymous I've removed it from the answer.
    $endgroup$
    – pacmaninbw
    May 5 at 21:05
















  • $begingroup$
    new is not normally faster than malloc. Do you have an implementation where it is?
    $endgroup$
    – Anonymous
    May 5 at 20:47










  • $begingroup$
    @Anonymous techdifferences.com/difference-between-new-and-malloc.html see execution.
    $endgroup$
    – pacmaninbw
    May 5 at 20:55










  • $begingroup$
    That source says "The new operator cuts off the execution time as it is an operator, not a function", which is confused — are they thinking it saves function call overhead or something? In reality, new is usually either exactly as fast as malloc (if it compiles to a malloc call) or slightly slower (if it adds an extra wrapper).
    $endgroup$
    – Anonymous
    May 5 at 21:03










  • $begingroup$
    @Anonymous I've removed it from the answer.
    $endgroup$
    – pacmaninbw
    May 5 at 21:05















$begingroup$
new is not normally faster than malloc. Do you have an implementation where it is?
$endgroup$
– Anonymous
May 5 at 20:47




$begingroup$
new is not normally faster than malloc. Do you have an implementation where it is?
$endgroup$
– Anonymous
May 5 at 20:47












$begingroup$
@Anonymous techdifferences.com/difference-between-new-and-malloc.html see execution.
$endgroup$
– pacmaninbw
May 5 at 20:55




$begingroup$
@Anonymous techdifferences.com/difference-between-new-and-malloc.html see execution.
$endgroup$
– pacmaninbw
May 5 at 20:55












$begingroup$
That source says "The new operator cuts off the execution time as it is an operator, not a function", which is confused — are they thinking it saves function call overhead or something? In reality, new is usually either exactly as fast as malloc (if it compiles to a malloc call) or slightly slower (if it adds an extra wrapper).
$endgroup$
– Anonymous
May 5 at 21:03




$begingroup$
That source says "The new operator cuts off the execution time as it is an operator, not a function", which is confused — are they thinking it saves function call overhead or something? In reality, new is usually either exactly as fast as malloc (if it compiles to a malloc call) or slightly slower (if it adds an extra wrapper).
$endgroup$
– Anonymous
May 5 at 21:03












$begingroup$
@Anonymous I've removed it from the answer.
$endgroup$
– pacmaninbw
May 5 at 21:05




$begingroup$
@Anonymous I've removed it from the answer.
$endgroup$
– pacmaninbw
May 5 at 21:05

















draft saved

draft discarded
















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f219738%2fhuffman-code-in-c%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020