簡體   English   中英

指向結構的指針(優先級隊列)

[英]Pointer to Pointer to Structure (Priority Queue)

我是一個初學者(在C ++中,我來自C(已有6個月的經驗)),我正在嘗試創建優先級隊列,但是有些問題不起作用。 當我啟動程序並進行編譯時,沒有錯誤。 但是屏幕上沒有任何打印內容,程序崩潰。

所以這是代碼:

PriorityQueue.h

using namespace std;

class PriorityQueue{
    private:
    struct pqentry_t{
        string value;
        float priority;
    };
    pqentry_t **_pqentry;
    int _size;
    int _next;

    public:
    PriorityQueue();
    ~PriorityQueue();
    void insert(string value, float priority);
    void printQueue();
};

PriorityQueue.cpp

#include <iostream>
#include <string>
#include "PriorityQueue.h"

#define SIZE 8
using namespace std;

PriorityQueue::PriorityQueue(){
    _size = SIZE;
    _next = 0;
    _pqentry = new pqentry_t*[_size];
}

PriorityQueue::~PriorityQueue(){
    delete[] _pqentry;
}

void PriorityQueue::insert(string value, float priority){
    _pqentry[_next]->value = value;    // this is probably not working
    _pqentry[_next]->priority = priority;
    _next++;
}

void PriorityQueue::printQueue(){
    for (int i = 0; i < _next; i++){
            cout << "Value: " << _pqentry[i]->value << endl
                 << "Priority: " << _pqentry[i]->priority << endl;
        }
        cout << endl;
}

main.cpp

#include <iostream>
#include <string>
#include "PriorityQueue.h"

using namespace std;

int main()
{
    PriorityQueue pq;
    pq.insert("Banana", 23);
    pq.printQueue();
}

我想,我知道錯誤在哪里,在PriorityQueue.cpp中,這里:

_pqentry[_next]->value = value;
_pqentry[_next]->priority = priority;

但是我不知道出了什么問題,也無法解決。 編譯器說沒有錯誤。

我希望你能幫幫我。 提前致謝!

您確實分配了_pqentry成員,但還需要分配該數組的每個條目,例如:

_pqentry [_next] =新的pqentry_t;

在寫之前。 並且不要忘記刪除那些:)

看起來您在構造函數中創建了指向pqentry_t的指針數組,但是您的insert方法期望它是_pqentry結構本身的數組。 您沒有為pqentry_t元素本身分配空間,因此當您嘗試在insert方法中取消引用它們時,程序崩潰。

嘗試將類中_pqentry的定義更改為pqentry_t * _pqentry,並將構造函數中的分配更改為新的pqentry_t [size]。 這將使您的insert和printQueue方法可以在寫入_pqentry時訪問它們。

暫無
暫無

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

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