The difference between the custom comparison function of the STL priority queue and the custom comparison function of the generic algorithm such as sort ()

Source: Internet
Author: User

Objective

  

Recently in the brush algorithm problem, often need to custom comparison function as a function object into the STL, encountered the following problem:

The comparison function of the generic algorithm sort () is so written:

//sort () to implement a comparison function in which the relationship between elements is incrementedstructcmp{BOOL operator() (Constt& A,Constt& b)Const    {        returnA.x <b.x; }};//or soBOOL operator< (Constt& A,Constt& b)Const {    returnA.x <b.x; }

The comparison function in the priority queue is written like this:

//Priority_queue A comparison function that implements an increment of the relationship between elements (to implement the minimum heap)structCMP {
DataType x; BOOL operator() (Constt& A,Constt& b)Const { returna.x >b.x; }}//or sostructT {type_2 x; FriendBOOL operator< (ConstT&a,Constt& b)Const { returna.x >b.x; }}

The same is the incremental relationship that implements the element "precursor < successor", why One is "a.x < b.x", one is "a.x > b.x"?

Analyze sort ()

Take sort () to analyze, sort the generic algorithm of the Class A lot of, their CMP notation is similar, here first see a bubble sort realizes increment relation such as <1, 2, 3. > notation, Law One: when the incoming class compare is a CMP is the function object, it overloads () makes the *current, *next "<" comparison, if the relationship of two elements does not meet "<", then the interchange.

#include <iostream>Template<classBidirectionalit,classcompare>//Bidirectional iteratorvoidBubble_sort (bidirectionalit First, Bidirectionalit last, Compare comp) { for(; First! = Last;--Last ) for(Bidirectionalit current = First, next = first; ++next! = last; + +)Current )if(!comp (*current, *next)) Std::swap (*current, *next); } }//You can write this .structCMP {BOOLOprator () (intAintb) {returnA <b; }};//or write like this .BOOLCMP (intAintb) {    returnA <b;} 

Word, the elements are arranged according to the logical relationships defined in the CMP.

Although sort () is implemented with a fast row + heap + insert instead of bubbling, the principle is the same.

Analysis Priority_queue

  

Now let's take a look at the priority queue.

STL Priority Queue Template: Priority_queue<type, Container, functional>, the parameters correspond to the element type, the container type, the comparison function respectively.

Note that the priority queue is not the STL container, but is implemented by the underlying container vector/deque, by default it is implemented with Max-heap, and Max-heap is a fully binary tree implemented by the vector, something called an adapter (adapter).

In the priority queue, the default high priority in the first-out queue, the specific action is to use the function object less<> overloaded with "<", so the high and low priority is determined by "<", so when we write as follows:

priority_queue<int> pqueue;

By using the operator < know that the element keyword is high in priority, this is the maximum heap. If you take an element from the top of the heap and then get a sequence, the relationship of the elements in the sequence is decremented.

What do we want the relationship of the element to be incrementing?

The first approach is to use the function object greater<> opposite the less<> action.

The second approach is to use a custom comparison function that enables you to define the precedence of a custom data type.

2-1. To compare the priority of an element by overloading the operator < operator

struct t{    DataType key;     BOOL operator < (constconst t& b) {        return a.key > b.key;    }};

The logic is this: Suppose A.key > B.key is TRUE, because the default is the maximum heap, at which point the priority queue will be considered a < B, that is, the priority of B is higher than a, so B will be first out of the team, so that the implementation of the keyword small elements first out of the team. The last output sequence is incremented by the keyword.

2-2. By overloading operator () to define the priority of the element.

struct cmp{    booloperator () (constconst const {         return a.x > b.x;    }};

Logic and 2-1 are the same. The purpose of this overload () is to make the CMP a function object like less<> (essentially inherited from Less<>), as a new comparison level rule to pass in the form of a third parameter priority_queue Priority_queu E in.

   

Summarize

The "comparison" concept of the priority queue and the "implemented by Max-heap" feature make it necessary to write in the custom comparison function: "a.x>b.x".

Extended Reading

Always let the comparison function return false for equal values (from effective C + +)

What is the specific operation of the sort in C + + using a custom comparison function?

The difference between the custom comparison function of the STL priority queue and the custom comparison function of the generic algorithm such as sort ()

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.