When an object in the queue has a higher priority than other objects, it needs to use a priority queue before other objects are first out of the queue regardless of where they are located.
Like the next implementation method
-Insert at the end of the pair, and traverse the entire queue when the team
-Sort when inserted, fixed at team head or tail
-use two fork to find tree
-Use two fork heap
Often at last the most important
The heap is a fully binary tree and can be implemented well using arrays. (Vector better, no need to enlarge)
Template<TypeNameT>classbinaryheap{ Public:ExplicitBinaryheap (intCapacity = -);ExplicitBinaryheap (Const vector<T>&items);BOOLIsEmpty ()Const;//Assuming the smallest dequeue, you can also adjust the maximum ConstT & Findmin ()Const;voidInsertConstT & T);voidDeletemin ();voidDeletemin (T & T);voidMakeempty ();Private:intCurrentSize; vector<T> Array;voidBuildheap ();voidPercolatedown (inthole);};/ * The new element first finds the last position, guaranteed to be a fully binary tree, when it is smaller than its parent node, swapping the position when it is larger than the parent node, inserting a new element * /Template<TypeNameT>voidBinaryheap<t>::insert (ConstT &t) {intHole = ++currentsize; for(; hole >1&& T <Array[Hole/2]; Hole/=2)Array[Hole] =Array[Hole/2];Array[Hole] = t;}//Delete the smallest element in the heap, relying mainly on the Percolatedown to implement the filterTemplate<TypeNameT>voidBinaryheap<t>::d eletemin () {if(IsEmpty ())ThrowUnderflowexcption ();Array[1] =Array[currentsize--]; Percolatedown (1);}//Delete the smallest element in the heap and get the element, mainly rely on the percolatedown to realize the filterTemplate<TypeNameT>voidBinaryheap<t>::d eletemin (T & T) {if(IsEmpty ())ThrowUnderflowexcption (); t =Array[1];Array[1] =Array[currentsize--]; Percolatedown (1);}//Down filter functionTemplate<TypeNameT>voidBinaryheap<t>::p Ercolatedown (intHole) {intChild T t =Array[Hole]; for(; Hole *2< CurrentSize; Hole = child) {Child = hole *2;if(Child! = CurrentSize &&Array[Child +1] <Array[Child]) ++child;if(Array[Child] < TMP)Array[Hole] =Array[Child];Else Break; }Array[Hole] = tmp;}
Priority Queue (heap) Notes C + +