如何将映射从类构造函数传递到类中的另一个函数
How to pass a map from a class constructor to another function in the class
我需要将我在 huffman_tree::huffman_tree 构造函数底部创建的 map, mainMap 传递给函数 get_character_code((,以便我可以在该函数中使用它的内容。
我无法访问 main 函数,因为我们的老师正在使用驱动程序来测试我们的代码是否有效。
我是编程的新手,所以如果我措辞奇怪,我道歉。
#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 "";
}
map<char, string> mainMap;
应该是你的类的成员。这将允许您从类中的任何成员函数访问它。
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;
};
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何在qt中从另一个类调用函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 将 N-arg 函数包装到另一个函数中
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- C++从另一个函数退出函数
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- 在一个类中使用另一个类中的函数,而不在 c++ 中使用继承
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?