Priority_queue in STL

Source: Internet
Author: User
Class templatepriority_queue <queue> priority queue

Priority Queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering condition.

This context is similar toHeapWhere onlyMax heapElement can be retrieved (the one at the top inPriority queue) And elements can be inserted indefinitely.

Priority Queues are implementedContainer adaptors, Which are classes that use an encapsulated object of a specific iner class as itsUnderlying container, Providing a specific set of member functions to access its elements. elements arePoppedFrom"Back"Of the specific iner, which is known asTopOf the priority queue.

The underlying container may be any of the standard container class templates or some other specifically designed container class. the only requirement is that it must be accessible through random access iterators and it must support the following operations:

  • Front ()
  • Push_back ()
  • Pop_back ()


Therefore, the standard container class templates vector and deque can be used. By default, if no container class is specified for a participantPriority_queueClass, the standard container class template vector is used.

Support for random access iterators is required to keep a heap structure internally at all times. This is done automatically by the container adaptor by calling the algorithms make_heap, push_heap and pop_heap when appropriate.

In their implementation in the C ++ standard template library, Priority Queues take three template parameters:

1
2
template < class T, class Container = vector<T>,           class Compare = less<typename Container::value_type> > class priority_queue;

Where the template parameters have the following meanings:

  • T:Type of the elements.
  • Container:Type of the underlying container object used to store and access the elements.
  • Compare:Comparison class: A class such that the expressionComp (A, B), WhereCompIs an object of this class andAAndBAre elements of the container, returnsTrueIfAIs to be placed earlierBIn a strict weak ordering operation. This can either be a class implementingFunction call operatorOr a pointer to a function. This defaultsLess <t>, Which returns the same as applyingLess-than Operator(A <B).
    ThePriority_queueObject uses this expression when an element is inserted or removed from it (using push orpop, respectively) to grant that the element popped is always the greatest in the priority queue.


In the reference forPriority_queueMember functions, these same names (T,ContainerAndCompare) Are assumed for the template parameters.

Member Functions
(Constructor)
Construct priority queue (Public member function)
Empty
Test whether container is empty (Public member function)
Size
Return size (Public member function)
Top
Access top element (Public member function)
Push
Insert element (Public member function)
Pop
Remove top element (Public member function)

 

Priority_queue is a container adapter. Container adapter means that its underlying implementation relies on a specific container to store data. The container adapter only encapsulates the container to meet the needs of the context application. The container adapter calls its member functions to call the functions of the container. C ++ STL defines three types of iner adapter: Stack (LIFO), queue (FIFO), and priority_queue (max heap ). The default container encapsulated by priority_queue is vector.

Priority_queue is constructed as a large root heap and will automatically call "algorithm. the make_heap, push_heap, and pop_heap functions in the H "(mainly common algorithms in STL) file are adjusted to maintain the features of the large root heap. Because it is a large root heap, each call to the top () function will return the reference of the maximum value in priority_queue.

Note: priority_queue is defined in the header file "queue. H". Therefore, you must add

# Include <queue>

 

The following example demonstrates the internal storage structure of priority_queue:

// priority_queue::push/pop#include <iostream>#include <queue>using namespace std;int main (){  priority_queue<int> mypq;  mypq.push(30);  mypq.push(100);  mypq.push(25);  mypq.push(40);  cout << "Popping out elements...";  while (!mypq.empty())  {     cout << " " << mypq.top();     mypq.pop();  }  cout << endl;  return 0;}

 

 

From: http://www.cnblogs.com/vvilp/articles/1504436.html

In the priority queue, the element with the highest priority is the first-out queue.
By default, the standard library uses the <operator of the element type to determine the priority relationship between them.
The first and most common usage of priority queue:

Priority_queue <int> qi;

The <operator indicates that the priority of a large element in an integer is high.
The output result in Example 1 is: 9 6 5 3 2

Method 2:
In example 1, what if we want to output elements from small to large?
In this case, we can pass in a comparison function using the functional. H function object as the comparison function.

Priority_queue <int, vector <int>, greater <int> qi2;

Where
The second parameter is the container type.
The second parameter is a comparison function.
The output result in example 2 is: 2 3 5 6 9

Method 3:
Custom priority.

Struct Node
{
Friend bool operator <(node N1, node N2)
{
Return n1.priority <n2.priority;
}
Int priority;
Int value;
};

In this structure, value is the value and priority is the priority.
You can use the custom operator <operator to compare the priority of an element.
In Example 3, the output result is:
Priority Value
9 5
8 2
6 1
2 3
1 4
However, if the structure is defined as follows:

Struct Node
{
Friend bool operator> (node N1, node N2)
{
Return n1.priority> n2.priority;
}
Int priority;
Int value;
};

It will not compile (G ++ compiler)
Because the standard library uses the <operator of the element type by default to determine the priority relationship between them.
The <operator and> operator of the custom type is not directly related, so it cannot be compiled.

// Code list

 

# Include <iostream>
# Include <functional>
# Include <queue>
Using namespace STD;
Struct Node
{
Friend bool operator <(node N1, node N2)
{
Return n1.priority <n2.priority;
}
Int priority;
Int value;
};
Int main ()
{
Const int Len = 5;
Int I;
Int A [Len] = {3, 5, 9, 6, 2 };
// Example 1
Priority_queue <int> qi;
For (I = 0; I <Len; I ++)
Qi. Push (A [I]);
For (I = 0; I <Len; I ++)
{
Cout <QI. Top () <"";
Qi. Pop ();
}
Cout <Endl;
// Example 2
Priority_queue <int, vector <int>, greater <int> qi2;
For (I = 0; I <Len; I ++)
Qi2.push (A [I]);
For (I = 0; I <Len; I ++)
{
Cout <qi2.top () <"";
Qi2.pop ();
}
Cout <Endl;
// Example 3
Priority_queue <node> Qn;
Node B [Len];
B [0]. Priority = 6; B [0]. value = 1;
B [1]. Priority = 9; B [1]. value = 5;
B [2]. Priority = 2; B [2]. value = 3;
B [3]. Priority = 8; B [3]. value = 2;
B [4]. Priority = 1; B [4]. value = 4;

For (I = 0; I <Len; I ++)
Qn. Push (B [I]);
Cout <"Priority" <'\ t' <"value" <Endl;
For (I = 0; I <Len; I ++)
{
Cout <Qn. Top (). Priority <'\ t' <Qn. Top (). value <Endl;
Qn. Pop ();
}
Return 0;
}

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.