7

文字とそれに対応する値をマップに保存し、そのマップを優先キューに挿入することで、ハフマンコーディングを実装しようとしています。キューを宣言しようとすると、パラメーター変換エラーが発生します。パラメータとして正確に何を入力する必要がありますか?ここにあるのは私の最善の推測です。

void main()
{
 ifstream doc("doc.txt"); 
 map<char, int> C;
 char letter;
 while(!doc.eof()){
  doc.get(letter);
  if(letter >= 'a' && letter <= 'z')
   C[letter]++;
 }
 priority_queue<int, map<char,int>, greater<int> > Q(C); //also tried greater<map<char,int>>
 /*map<char, int>::const_iterator it;
 for(it = C.begin(); it != C.end(); it++)
  cout<<it->first<<" "<<it->second<<endl;*/
}

これを尋ねるのはちょっとばかげているように感じますが、徹底的にグーグルで調べても答えが得られませんでした。助けてくれてありがとう!

4

2 に答える 2

13

priority_queue の基礎となるコンテナーとしてマップを使用することはできません。vector と deque のみを使用できます (標準コンテナーから)。

したがって、コンテナ タイプは のようなものになりますvector<pair<char, int> >。次に、ペアの 2 番目のフィールドのみを考慮する、より少ない/より大きな操作が必要です。

于 2010-12-19T21:35:30.547 に答える
9

方法 1、functorを使用して、

#include <unordered_map>
#include <vector>
#include <iostream>
#include <queue>
using namespace std;

typedef pair<char, int> PAIR;

int main(int argc, char *argv[]) {
    unordered_map<char, int> dict = {{'a', 12}, {'b', 9}, {'c', 7}, {'d', 10},};
    struct cmp {
        bool operator()(const PAIR &a, const PAIR &b) {
            return a.second < b.second;
        };
    };
    priority_queue<PAIR, vector<PAIR>, cmp> pq(dict.begin(), dict.end());
    while (!pq.empty()) {
        PAIR top = pq.top();
        cout << top.first << " - " << top.second << endl;
        pq.pop();
    }
}

方法 2、関数とdecltype()それを使用する

auto cmp = [](const PAIR &a, const PAIR &b) {
    return a.second < b.second;
};
priority_queue<PAIR, vector<PAIR>, decltype(cmp)> pq(
        dict.begin(), dict.end(), cmp);

上記の例のpriority_queueは値でソートされ、

a - 12
d - 10
b - 9
c - 7
于 2016-10-22T11:14:17.947 に答える