C++ STL : Using map with priority_queue

标签 c++ stl map priority-queue huffman-code

我正在尝试通过将字母及其对应值保存到映射中然后将该映射插入到优先级队列中来实现霍夫曼编码。当我尝试声明我的队列时出现参数转换错误。我到底应该把什么作为参数?我这里有的是我最好的猜测。

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

我觉得问这个问题有点愚蠢,但彻底的谷歌搜索并没有给我答案。非常感谢您的帮助!

最佳答案

您不能将 map 用作 priority_queue 的底层容器:priority_queue 必须可以自由地对容器中的内容进行重新排序,而这对于 map 是不允许的。只能使用 vector 和 deque(来自标准容器)。

因此,容器类型类似于 vector<pair<char, int> > .然后,您需要一个 less/greater 操作,它只考虑该对的第二个字段。

关于C++ STL : Using map with priority_queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4485203/

相关文章:

c++ - 将析构函数信息存储到 void* 的合法方法

c++ - 使用 hash_map 时,在 STL 字符串上使用的最佳散列算法是什么?

c++ - STL 可迭代对象的迭代器循环宏

c++ - C++中的二维字符串

c++ - 如何使用Google Protobuf实现Map结构

map - Web 应用程序中的地理数据可视化

c++ - sqlite 和可能的空值

c++ - 根据作用域或非作用域枚举的隐式实例化

Java:通用过滤器映射函数

c++ - 'mem_fun' : is not a member of 'std'