Очередь с приоритетами не работает с Compare () - PullRequest
0 голосов
/ 01 декабря 2011

Я разработал очередь с приоритетами, но она не работает для некоторых тестовых случаев.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

template <class T1, class T2>
class priorityQueue {
private:
    vector<T1> dataContainer;

    class Compare {
    public:
    // Compare two elements .
        bool operator()(const T1& a, const T1& b) const {
        return a > b;
    }
    };

public:
    priorityQueue(vector<T1>& myV) : dataContainer(myV) {    
        make_heap(dataContainer.begin(), dataContainer.end(), Compare());
    }

    bool empty() const { return dataContainer.empty(); }
    // get the size of the queue 
    size_t size() const { return dataContainer.size(); }
    // get the element with the highest priority in the queue
    T1& top(){ return dataContainer.front();}
    // push an element into the qeueu 
    void enQueue(T1& element) {
        dataContainer.push_back(element);
        push_heap(dataContainer.begin(), dataContainer.end(), Compare());
    }
    // pop the element with the highest priority in the qeueu 
    void deQueue() {
        pop_heap(dataContainer.begin(), dataContainer.end(), Compare());
        dataContainer.erase(dataContainer.begin());
    }
    void printQ() {
        typename vector<T1>::iterator itr ; 
        cout << "the priorityQueue is : " << endl ;   
        for (itr = dataContainer.begin(); itr != dataContainer.end(); ++itr) {
            cout << *itr << "\t"; 
        }
        cout << endl ;      
    }
};

int main() {
    vector<int> aa;
    int a[4] = {5, 8, 3, 2};
    aa.assign(a, a+4);
    priorityQueue<int, bool> myQ(aa);  
    myQ.printQ(); 

    return 0; 
}

Класс сравнения не может изменить порядок приоритетов.

вывод для a > b должен быть 2 3 5 8.


ОБНОВЛЕНИЕ Проблема была решена, спасибо

1 Ответ

3 голосов
/ 01 декабря 2011

В операции dequeue() необходимо удалить элемент последний :

 void deQueue()
 {
       pop_heap(dataContainer.begin(), dataContainer.end(), Compare());
       dataContainer.pop_back();
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...