Below I have a bit of code for implementing Huffman compression. What I was curious about was if I could initialize the left
and right
pointers without including cstdlib
, or rather, if I could initialize an empty memory location for storing the left
and right
without using malloc.
Also, in my combine function, I do not want to use "NULL"
for the string parent node of my left and right, but would rather have an empty string. Will I have to make a new constructor for this? I get an error (basic_string::_M_construct null not valid
) when I replace "NULL"
with nullptr.
#include <string>
#include <cstdlib>
#ifndef PRIORITY_NODE
#define PRIORITY_NODE
namespace Huffman
{
class PriorityNode
{
private:
std::string key; // The character sequence to compress
long frequency = 0; // The frequency of the character sequence
PriorityNode* left = (PriorityNode*)malloc(sizeof(PriorityNode));
PriorityNode* right = (PriorityNode*)malloc(sizeof(PriorityNode));
public:
PriorityNode(std::string k, long f): frequency(f), key(k){};
std::string getKey() const{ return key;}
long getFrequency() const{ return frequency;}
void setLeft(const PriorityNode& left){*this->left = left;}
void setRight(const PriorityNode& right){*this->right = right;}
PriorityNode& getLeft() const{ return *left;}
PriorityNode& getRight() const{ return *right;}
friend PriorityNode combine(const PriorityNode& lhs, const PriorityNode& rhs)
{
long ret_freq = lhs.getFrequency() + rhs.getFrequency();
PriorityNode ret = PriorityNode("NULL", ret_freq);
ret.setLeft(lhs);
ret.setRight(rhs);
return ret;
};
};
}
#endif
Aucun commentaire:
Enregistrer un commentaire