c++ - 如何将映射从类构造函数传递到类中的另一个函数
问题描述
我需要将我在 huffman_tree::huffman_tree 构造函数底部创建的地图 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;
};
推荐阅读
- python - 使用 Python 和 Flask 连接 SFTP 服务器有困难吗?
- mysql - MySQL: ORDER BY column DESC LIMIT (SELECT COUNT(*) FROM table);
- google-cloud-firestore - Firestore 模拟器 - “不允许使用三元运算符。”
- pytorch - 需要 pytorch 帮助一次用 N 个内核对 N 个图像进行 2D 卷积
- typescript - 动作中使用的类型语法的机制是什么?
- python - Pygame Mixer 不播放音频
- java - 按键后调用方法的问题
- javascript - 使用节点和mysql。在字符串变量处插入失败
- laravel - 密码确认不匹配?
- c++ - 使用 std::is_same_v 而不是重载或专业化有任何潜在问题吗?