[英]How to insert elements from a structure into a min heap priority queue
I am making a file compressor using Huffman Algorithm in C++.我正在使用 C++ 中的 Huffman 算法制作文件压缩器。 I have calculated the character frequency, but now I am having difficulty in pushing it into a min heap priority queue.
我已经计算了字符频率,但现在我很难将它推入最小堆优先级队列。 I want to sort the inserted elements by frequency.
我想按频率对插入的元素进行排序。 Every time I execute the code, it gives the error:
每次我执行代码时,它都会给出错误:
Error C2676 binary '>': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator
I have tried almost every way mentioned on this website, yet I still cannot get rid of this error.我几乎尝试了这个网站上提到的所有方法,但我仍然无法摆脱这个错误。
Here is my code:这是我的代码:
#include<iostream>
#include<string>
#include<queue>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
struct node
{
char c; //character in the string
int f; //Frequency of character in the string
node* next;
node* left, * right; //left and right child of binary tree respectively
node()
{
f = 0;
left = NULL;
right = NULL;
c = NULL;
next = NULL;
}
bool operator>(const node& a)
{
return a.f > f;
}
};
class Huffman
{
string text; //The text that will be encoded
priority_queue <node> pq;
public:
Huffman()
{
}
void StringInput()
{
cout << "Enter the string you want to encode:";
getline(cin, text);
}
//Function which will calculate the frequency of characters in the string entered by the user
void CharacterFrequency()
{
for (int i = 0; i < text.length(); i++)
{
int sum = 0;
for (int j = 0; j < text.length(); j++)
{
if (j < i and text[i] == text[j])
{
break;
}
if (text[i] == text[j])
{
sum++;
}
}
if (sum != 0)
{
PriorityQueue(text[i], sum);
}
}
}
void PriorityQueue(char ch, int freq)
{
node n;
n.c = ch;
n.f = freq;
pq.push(n);
}
};
int main()
{
Huffman obj;
obj.StringInput();
obj.CharacterFrequency();
return 0;
}
I will be grateful for any help in this regard.我将不胜感激在这方面的任何帮助。
There are two issues:有两个问题:
Issue 1 : You are not declaring the priority queue correctly.问题 1 :您没有正确声明优先级队列。
If you want to add a custom comparison, you need to specify that in the template:如果要添加自定义比较,则需要在模板中指定:
std::priority_queue <node, std::vector<node>, std::greater<node>> pq;
Now the node::operator >
will be used.现在将使用
node::operator >
。
Issue 2 : The operator >
should be a const
function:问题 2 :
operator >
应该是一个const
函数:
bool operator>(const node& a) const
{
return a.f > f;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.