[STL learning] detailed explanation of priority queue and C ++ programming implementation

Source: Internet
Author: User
Introduction to priority queue

A priority queue is a queue with an ownership concept. It allows you to add elements at the bottom, remove elements at the top, and delete elements.

The elements in the priority queue are not arranged in the order of addition, but automatically arranged according to the weight of the elements. The highest weight is at the top.

By default, Priority Queues are completed using a large top heap. For more information about heap, see STL heap explanation and programming implementation.


The priority queue completes all its work with the bottom container. It has this "modifying something interface, forming another style" and becomes the adapter ). In STL, Priority Queues are classified as containers instead of containers.
Adapter ).


Priority queue definition in SGI STL

Complete Code defined:

Template <class T, class sequence = vector <t>, class compare = less <typename sequence: value_type> class priority_queue {public: typedef typename sequence: value_type; typedef typename sequence: size_type; typedef typename sequence: Reference reference; typedef typename sequence: const_referenceconst_reference; protected: sequence C; // underlying container compare comp; // element size comparison standard public: Pr Iority_queue (): C () {} explicit priority_queue (const compare & X): C (), comp (x) {}// make_heap () used below (), push_heap () and pop_heap () are generic algorithms // note that any construction generates an implicit representation heap immediately in the underlying container. Template <class inputiterator> priority_queue (inputiterator first, inputiterator last, const compare & X): C (first, last), comp (x) {make_heap (C. begin (), C. end (), comp);} template <class inputiterator> priority_queue (inputiterator first, inputiterator last): C (first, last) {make_heap (C. begin (), C. end (), comp);} bool empty () const {return C. empty ();} size_typesize () const {return C. size ();} Const_referencetop () const {return C. front ();} void push (const value_type & X) {_ stl_try {// push_heap is a generic algorithm. First, use push_back () of the underlying container () push the new element // into the receiver, and then rearrange the heap. See C ++ primer p.1195. C. push_back (x); push_heap (C. begin (), C. end (), comp); // push_heap is a generic algorithm }__ stl_unwind (C. clear ();} void POP () {_ stl_try {// pop_heap is a generic algorithm that extracts an element from heap. Instead of actually popping up the element //, It reassembles the heap and then retrieves the element popped up/From the pop_back () of the underlying container. See C ++ primer p.1195. Pop_heap (C. Begin (), C. End (), comp); C. pop_back () ;}_ _ stl_unwind (C. Clear ());}};

Priority queue programming implementation (C plus)

Here, we use C ++ to program the simple version of priority queue. Heap. h In the previous blog is used:

// STL heap Algorithm Implementation (Big Top heap) // header file containing the vector container: heap uses vector to store elements # include <vector> # include <iostream> # include <functional> # define max_value 999999 // a large value, the first position (max heap) const int startindex = 1; // The starting index of heap elements in the container using namespace STD; // heap class definition // default comparison rule lesstemplate <class elemtype, class compare = less <elemtype> class myheap {PRIVATE: vector <elemtype> heapdatavec; // The Int numcounts container for storing elements; // The number of elements in the heap compare comp; // comparison rule public: myh EAP (); vector <elemtype> & getvec (); void initheap (elemtype * data, const int N); // initialize void printfheap (); // output heap element void makeheap (); // heap creation void sortheap (); // heap Sorting Algorithm void pushheap (elemtype ELEM ); // Insert the element void popheap () into the heap. // extract the element void adjustheap (INT childtree, elemtype adjustvalue) from the heap ); // adjust the subtree void percolateup (INT holeindex, elemtype adjustvalue); // perform the upstream operation void setnumcounts (INT Val); // set the number of elements in the heap to be constructed }; template <class elemty PE, class compare> myheap <elemtype, compare >:: myheap (): numcounts (0) {heapdatavec. push_back (max_value);} template <class elemtype, class compare> vector <elemtype> & myheap <elemtype, compare >:: getvec () {return heapdatavec;} template <class elemtype, class compare> void myheap <elemtype, compare >:: initheap (elemtype * data, const int N) {// copy the element data to the vector for (INT I = 0; I <n; ++ I) {heapdatavec. push_back (* (Data + I); ++ num Counts ;}} template <class elemtype, class compare> void myheap <elemtype, compare >:: printfheap () {cout <"heap:"; for (INT I = 1; I <= numcounts; ++ I) {cout 


Priorityqueue. h:

# Include "heap. H "// priority queue class definition // default: Maximum template with the smallest weight <class elemtype, class compare = less <elemtype> class mypriorityqueue {PRIVATE: myheap <elemtype, compare> heap; // implement public with heap at the underlying layer: // constructor mypriorityqueue (elemtype * data, int N); // determine whether the priority queue is empty int empty () {return heap. getvec (). size ()-1;} // return priority queue size long SIZE () {return heap. getvec (). size ()-1;} // note that the first element of the underlying container is invalid. // obtain the elemtype top () {return heap, the element of the priority queue header. getvec () [startindex];} // Add the element void push (const elemtype & Val); // The first element void POP (); myheap <elemtype, compare> & getheap () {return heap ;};}; template <class elemtype, class compare> mypriorityqueue <elemtype, compare >:: mypriorityqueue (elemtype * data, int N) {heap. initheap (data, n); heap. makeheap (); heap. sortheap ();} template <class elemtype, class compare> void mypriorityqueue <elemtype, compare>: Push (const elemtype & Val) {heap. setnumcounts (heap. getvec (). size ()-1); // exclude the heap element of the container header. makeheap (); heap. pushheap (VAL); heap. sortheap ();} template <class elemtype, class compare> void mypriorityqueue <elemtype, compare >:: POP () {heap. getvec (). erase (heap. getvec (). begin () + 1); // deletes the heap element of the queue header. setnumcounts (heap. getvec (). size ()-1); // exclude the heap element of the container header. makeheap (); heap. sortheap ();}



Priorityqueuetest. cpp:

#include "PriorityQueue.h"#include <iostream>#include <string>using namespace std;int main(){const int n = 9;int data[n] = {0,1,2,3,4,8,9,3,5};MyPriorityQueue<int> *priorityObj1 = new MyPriorityQueue<int>(data,n);cout << "Current Heap: " << endl;for (int i = 1;i <= priorityObj1->size();++i){cout << priorityObj1->getHeap().getVec()[i] << " ";}cout << endl;cout << "Size = " << priorityObj1->size() << endl;cout << "Top element = " << priorityObj1->top() << endl;priorityObj1->pop();cout << "After pop one element:" << endl;cout << "Size = " << priorityObj1->size() << endl;cout << "Top element = " << priorityObj1->top() << endl;cout << "Current Heap: " << endl;for (int i = 1;i <= priorityObj1->size();++i){cout << priorityObj1->getHeap().getVec()[i] << " ";}cout << endl;priorityObj1->pop();cout << "After pop one element:" << endl;cout << "Size = " << priorityObj1->size() << endl;cout << "Top element = " << priorityObj1->top() << endl;cout << "Current Heap: " << endl;for (int i = 1;i <= priorityObj1->size();++i){cout << priorityObj1->getHeap().getVec()[i] << " ";}cout << endl;priorityObj1->push(7);cout << "After push one element 7:" << endl;cout << "Size = " << priorityObj1->size() << endl;cout << "Top element = " << priorityObj1->top() << endl;cout << "Current Heap: " << endl;for (int i = 1;i <= priorityObj1->size();++i){cout << priorityObj1->getHeap().getVec()[i] << " ";}cout << endl;delete priorityObj1;}

Running result (win7 + vs2008 ):

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.