因此,我们的任务是为文本/数字的.txt编写压缩alg (大概是通过霍夫曼编码,因为我们的教授非常含糊)
我将所有的行都作为键放在一个映射中,频率作为它们的值。我对如何从这里开始有点粗略,因为地图是按键而不是值组织的,我应该使用不同的数据结构(而不是地图),或者每次我想要添加到树中时,只找到两个最小的最小值是否足够简单?下面的代码,任何帮助都会很棒!
#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;
}
发布于 2016-10-28 13:22:13
要查找min
值,可以使用Priority Queue。
A Priority Queue是一种数据结构,可以从一组元素中给出最小值或最大值。在其中查找或插入需要使用
O(log(n))
。因此,在这种情况下,它可能是一个完美的选择。
C++有自己的内置优先级队列。
以下是C++中的priority_queue
的一个简单示例。
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue <int> Q;
Q.push(10);
Q.push(7);
Q.push(1);
Q.push(-3);
Q.push(4);
while(!Q.empty()){ // run this loop until the priority_queue gets empty
int top = Q.top();
Q.pop();
cout << top << ' ';
}
cout << endl;
return 0;
}
输出
10, 7, 4, 1, -3
如你所见,这是按升序排列的。这是因为:
默认情况下,优先级队列提供的值最高。
因此,您可以重载优先级队列,或者一个非常聪明的技巧是通过反转符号来存储值,并在从队列中弹出它们之后,可以再次反转符号。
https://stackoverflow.com/questions/37232954
复制