【问题标题】:Huffman Coding Algorithm/Data Structures霍夫曼编码算法/数据结构
【发布时间】: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;
}

【问题讨论】:

标签: algorithm data-structures huffman-code


【解决方案1】:

要查找min 值,您可以使用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

您可以注意到这是按升序排列的。 那是因为:

默认情况下,优先队列给出最高值。

因此,您可以重载优先级队列,也可以采用一个非常聪明的技巧,通过反转它们的符号来存储值,然后在将它们从队列中弹出后,您可以再次反转符号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    相关资源
    最近更新 更多