fork download
  1. #include <vector>
  2. #include <iostream>
  3. #include <memory>
  4. class huffman_node
  5. {
  6. public:
  7. bool internal_;
  8. char symbol_;
  9. int freq_;
  10. std::unique_ptr<huffman_node> left_;
  11. std::unique_ptr<huffman_node> right_;
  12. public:
  13. huffman_node() : internal_(true), symbol_('?') {}
  14. huffman_node(char symb, int freq): internal_(false),
  15. symbol_(symb),
  16. freq_(freq) {}
  17. huffman_node(huffman_node& other)
  18. {
  19. internal_ = other.internal_;
  20. symbol_ = other.symbol_;
  21. freq_ = other.freq_;
  22. left_ = std::move(other.left_);
  23. right_ = std::move(other.right_);
  24. }
  25. huffman_node & operator=(huffman_node& other)
  26. {
  27. internal_ = other.internal_;
  28. symbol_ = other.symbol_;
  29. freq_ = other.freq_;
  30. left_ = std::move(other.left_);
  31. right_ = std::move(other.right_);
  32. return *this;
  33. }
  34. ~huffman_node() {}
  35. };
  36.  
  37. class huffman_encoder
  38. {
  39. public:
  40. void make_huffman(
  41. const std::vector<int>& freq,
  42. const std::vector<char>& symb)
  43. {
  44. std::vector<std::unique_ptr<huffman_node>> nodes;
  45. for (int i = 0; i < freq.size(); ++i)
  46. {
  47. std::unique_ptr<huffman_node> ph(new huffman_node(symb[i], freq[i]));
  48. if (ph)
  49. nodes.push_back(std::move(ph));
  50. }
  51. print_node(nodes);
  52. }
  53.  
  54. void print_node(std::vector<std::unique_ptr<huffman_node>>& nodes)
  55. {
  56. for (auto &node : nodes)
  57. {
  58. std::cout << "symbol: " << node->symbol_ << " frequency: " << node->freq_ << std::endl;
  59. }
  60. }
  61. };
  62.  
  63. int main()
  64. {
  65. std::vector<char> sym = {'a', 'b', 'c', 'd'};
  66. std::vector<int> freq = { 5, 1, 3, 9};
  67. huffman_encoder he;
  68. he.make_huffman(freq, sym);
  69. return 0;
  70. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
symbol: a frequency: 5
symbol: b frequency: 1
symbol: c frequency: 3
symbol: d frequency: 9