簡體   English   中英

如何將結構中的元素插入最小堆優先級隊列

[英]How to insert elements from a structure into a min heap priority queue

我正在使用 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;
}

我將不勝感激在這方面的任何幫助。

有兩個問題:

問題 1 :您沒有正確聲明優先級隊列。

如果要添加自定義比較,則需要在模板中指定:

std::priority_queue <node, std::vector<node>, std::greater<node>> pq;

現在將使用node::operator >


問題 2operator >應該是一個const函數:

bool operator>(const node& a) const
{
    return a.f > f;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM