0

我正在构建一个霍夫曼编码程序,当我尝试运行到目前为止的代码时,它只会给我一个警告,即频率映射对象 .begin() 不存在。

哈夫.h

#ifndef HuffPuff_Huff_h
#define HuffPuff_Huff_h
//---Include---
#include <iostream>
#include <vector>
#include <set>
using namespace std;

//---Node---
struct Node {
    int weight;
    char litteral;
    string symbol;
    Node* childL;
    Node* childR;
    void set_node(int w, char l, Node* L, Node* R){
        weight = w;
        litteral = l;
        childL = L;
        childR = R;
    }
    bool operator>(Node & r){
        if(this->weight > r.weight)
            return true;
        return false;
    }
};

//---Code---
struct Code {
    string symbol;
    char content;
};

//---HuffClass---
class Huff {
private:
    typedef pair<char, int> c_pair;
    vector<Code> code;
    string content;
    void copy_to(c_pair c);
public:
    Huff(string);
    ~Huff();

    string compress();
    bool set_content();
    string get_content();
    string get_compress();
};


#endif

哈夫.cpp

//---Include---
#include <iostream>
#include <vector>
#include "Huff.h"
#include <map>
#include <set>
using namespace std;

//---|+ -|---
Huff::Huff(string c): content(c){}
Huff::~Huff(){}

//---Compress---
struct CopyTo {
    vector<Node*>* & nodes;
    CopyTo(vector<Node*>* & c):nodes(c){}
    void operator()(pair<char, int> c){
        Node * n = new Node;
        n->set_node(c.second, c.first, NULL, NULL);
        nodes->push_back(n);
    }
};
void show_freq(pair<char, int>  p) {
    cout << p.first << "\t" << p.second << endl;
}
/*void show_freq(Node*  p) {
    cout << p->litteral << "\t" << p->weight << endl;
}*/

string Huff::compress(){   
    vector<Node *>* nodes; // Vector of nodes for later use
    map<char, int>* freq = new map<char, int>; //  Map to find weight of nodes
    for(int i = 0; i < content.length(); i++) 
        (*freq)[content[i]]++; 
    for_each(freq->begin(), freq->end(), show_freq);
    CopyTo copyto(nodes); //Copy map elements to nodes in this and next one
    for_each(freq->begin(), freq->end(), copyto);
    delete freq;
    Node p;
    while(nodes->size() != 1){ //Sorts nodes by weight and then removes two of them and replaces them with one
        sort(nodes->begin(), nodes->end());
        vector<Node *>::iterator beg = nodes->begin();
        int w= (**beg).weight + (**beg++).weight;
        Node* p = new Node;
        p->set_node(w, '*', *nodes->begin(), *(nodes->begin()++));
        nodes->erase(nodes->begin(), nodes->begin()+2);
        nodes->push_back(p);
        //for_each(nodes->begin(), nodes->end(), show_freq);
        cout << "--------------" << endl;
    }
    Node* root = *nodes->begin();
    return "110";
}

Main.cpp

int main(){
Huff mike("Testing-");
mike.compress();
}
4

1 回答 1

0

算法头包含在哪里?

在线编译 结果

编译输出:
source.cpp:在成员函数'std::string Huff::compress()'中:
source.cpp:76:39:警告:有符号和无符号整数表达式之间的比较[-Wsign-compare] source.cpp: 94:11:警告:未使用的变量 'root' [-Wunused-variable]
执行输出:
- 1
T 1
e 1
g 1
i 1
n 1
s 1
t 1

于 2012-07-06T20:46:54.740 回答