【发布时间】:2022-06-10 22:29:11
【问题描述】:
我正在使用 C++ 中的 Huffman 算法制作文件压缩器。我已经计算了字符频率,但现在我很难将它推入最小堆优先级队列。我想按频率对插入的元素进行排序。每次执行代码都会报错:
Error C2676 binary '>': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator
我几乎尝试了这个网站上提到的所有方法,但我仍然无法摆脱这个错误。
这是我的代码:
#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;
}
如果在这方面提供任何帮助,我将不胜感激。
【问题讨论】:
-
就像错误所说的那样,它找不到
operator >的node类型。 C++ 不会为您制作这些(如果您默认 C++20 中引入的宇宙飞船运算符,它会为您制作),因此您必须自己制作一个 -
我也试过了,但它给出了同样的错误。
-
请把贴出的代码中多余的空行去掉。
-
@MuhammadTaimoor 我也试过了 -- 显然你的尝试是错误的。由于它是错误的,请发布此尝试。
-
@PaulMcKenzie 问题已编辑以包含特定尝试。
标签: c++ stl priority-queue min-heap