Reputation: 31
I need to pass the map, mainMap, that I created at the bottom of my huffman_tree::huffman_tree constructor to the function get_character_code() so I can use its contents in that function.
I do not have access to the main function because our teacher is using a driver program to test if our code works or not.
I am new to programming in general so if I worded something weird I apologize.
#ifndef _HUFFMAN_TREE_H_
#define _HUFFMAN_TREE_H_
#include <iostream>
class huffman_tree {
public:
huffman_tree(const std::string &file_name);
~huffman_tree();
std::string get_character_code(char character) const;
std::string encode(const std::string &file_name) const;
std::string decode(const std::string &string_to_decode) const;
};
#endif
huffman_tree::huffman_tree(const std::string &file_name)
{
int count[95] = { 0 };
int x;
ifstream inFile(file_name);
stringstream buffer;
buffer << inFile.rdbuf();
string text = buffer.str();
inFile.close();
int length = text.length();
for (int i = 0; i < length; i++)
{
if (text[i] >= ' ' && text[i] <= '~')
{
x = text[i] - ' ';
count[x]++;
}
}
int temp[95][2] = { 0 };
int numbers = 0;
for (int i = 0; i < 95; i++)
{
if (count[i] > 0)
{
temp[numbers][0] = count[i];
temp[numbers][1] = (i + ' ');
numbers++;
}
}
vector<char> characters;
vector<int> frequency;
for (int i = 0; i < numbers; i++)
{
frequency.push_back(temp[i][0]);
characters.push_back((char)(temp[i][1]));
}
map<char, string> mainMap;
mainMap = HuffmanCodes(characters, frequency, numbers);
}
std::string huffman_tree::get_character_code(char character) const
{
for (itr = mainMap.begin(); itr != mainMap.end(); ++itr)
{
if (itr->first == character)
{
return itr->second;
}
}
return "";
}
Upvotes: 0
Views: 49
Reputation: 217145
map<char, string> mainMap;
should be a member of your class. That'll allow you to access it from any member function in the class.
class huffman_tree {
public:
huffman_tree(const std::string& filename);
~huffman_tree();
std::string get_character_code(char character) const;
std::string encode(const std::string& filename) const;
std::string decode(const std::string& string_to_decode) const;
private:
std::map<char, std::string> mainMap;
};
Upvotes: 2