C ++ STL: using map with priority_queue

I am trying to implement Huffman coding by storing letters and their corresponding values ​​in a map, and then inserting the map in the priority queue. I get a parameter conversion error when I try to declare a queue. What exactly should I specify as parameters? What I had here was my best guess.

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;*/
}

I feel stupid asking about this, but a thorough Google search did not give me an answer. Thank you very much for your help!

+3
source share
2 answers

priority_queue: priority_queue , . deque ( ).

, vector<pair<char, int> >. / , .

+8

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() it

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
+1

Source: https://habr.com/ru/post/1781143/


All Articles