【发布时间】:2016-05-14 23:32:11
【问题描述】:
因此,我们的任务是为文本/数字的 .txt 编写压缩算法(可能是通过霍夫曼编码,因为我们的教授非常模糊)
我将所有行作为地图中的键,并将频率作为它们的值。我对如何从这里开始有点粗略,因为地图是按键而不是值按顺序组织的 我应该使用不同的数据结构(不是地图)还是每次我想添加到树时只需找到 2 个最小的最小值就足够容易了?下面的代码,任何帮助都会很棒!
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
int main()
{
vector <string> words;
map <string, int> store;
ifstream infile("file.txt");
string text;
while (getline(infile, text))
{
istringstream iss(text);
string input;
if (!(iss >> input))
break;
words.push_back(input);
}
int freq = 0;
while (!words.empty())
{
string check = words[0];
if(check == "") //make sure not reading a blank
{
words.erase(remove(words.begin(), words.end(), "")); //remove all blanks
continue; //top of loop
}
check = words[0];
freq = count(words.begin(), words.end(), check);//calculate frequency
store.insert(pair<string, int>(check, freq)); //store words and frequency in map
words.erase(remove(words.begin(), words.end(), check)); //erase that value entirely from the vector
}
map<string, int>::iterator i;
for(i = store.begin(); i != store.end(); ++i)
{
cout << "store[" << i ->first << "] = " << i->second << '\n';
}
return 0;
}
【问题讨论】:
-
你需要把你的数据统计后放入节点。在那之后,一切都应该清楚了。不使用节点就不可能构建一棵树。要将数据放入节点中,首先您需要一个类来保存单个映射条目或它所代表的数据。
-
@greenteam 你可以很容易地在 geeks for geeks 上找到这个,这里:- geeksforgeeks.org/greedy-algorithms-set-3-huffman-coding
-
geeksforgeeks.org/greedy-algorithms-set-3-huffman-coding-set-2 因为实现霍夫曼编码算法的方法不止一种。另外,我认为您应该搜索数据压缩技术和算法以找到最佳且理想的解决方案。
标签: algorithm data-structures huffman-code