How to make STL's priority_queue fixed-size

前端 未结 5 767
北海茫月
北海茫月 2020-12-17 18:41

I am creating a simple game and I use std::priority_queue for giving commands to squads (every squad has a priority_que

5条回答
  •  孤城傲影
    2020-12-17 19:31

    One idea is to create a min priority queue and use the size() method to only fill the priority queue to the required level. Something like this:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    struct Compare {
        // priority queue is max heap by default, use compare
        // to make it minheap
        bool operator() (const int& a, const int& b) {
            return a>b;
        }
    };
    
    typedef priority_queue, Compare> pqSize;
    
    void priorityQueueFixedSize(pqSize& pq, int size, vector& vec) {
        for (int i=0;i pq.top()) {
                    pq.pop();
                    pq.push(vec[i]);
                }
            }
        }
    }
    
    void printPQ(pqSize& pq) {
        while (!pq.empty()) {
            cout << pq.top() << " ";
            pq.pop();
        }
        cout << endl;
    }
    
    int main() {
        vector vec(20,0);
        for (int i=0;i

    This way only the maximum 10 elements will be held in the priority queue.

提交回复
热议问题