dimanche 3 mai 2015

Pointer to Pointer to Structure (Priority Queue)

I'm a beginner (in C++, I'm coming from C (6 months experience)) and I'm trying to create a priority queue, but something is not working. When I start the program and compile it, there are no errors. But there is nothing printed on the screen and the program crashes.

So here is the code:

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[_next]->value << endl
                 << "Priority: " << _pqentry[_next]->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();
}

I think, I know where the error is, in the PriorityQueue.cpp, here:

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

But I don't know what's wrong and I can't fix it. The compiler says there are no errors.

I hope, you can help me. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire