"Algorithm learning" old algorithm, new posture, stl--heap

Source: Internet
Author: User

A "heap" is a familiar data structure that maintains the set's extrema within the time of \ (O (log\;n) \).

This is the old routine, the specific internal implementation I will not talk about.

I generally use the priority_queue in the queue library, which is the STL's priority queue, to implement the heap, but recently I found a new STL container with smaller constants and more convenient operations relative to the priority queue.

It's the heap.

About HEAP,STL provides 4 functions that are defined in the algorithm library. Each of them is:

Like sort , where _first,_last are heads, tail pointers or iterators (corresponding to vectors or queue), and _cmp represents the size relationship function between elements.

Similar to sort, the element in the heap is an interval of [_first, _last], if memory is not contiguous, or at least a randomly accessible iterator (such as a vector).

Where _cmp are not necessary.

It is also important to note that these functions are maintained by Dagen (that is, the father value is larger than the child's heap, also known as the largest heap).

Build heap:

Make_heap (_first, _last, _cmp)

To add elements to the heap:

Push_heap (_first, _last, _cmp)

To add an element first, call the function again.

To delete an element in the heap:

Pop_heap (_first, _last, _cmp)

To call the function first, then delete (do not delete, as long as the guarantee that there will be no memory leaks or other bugs).

Heap Sort:

Sort_heap (_first, _last, _cmp)

The sequence, like the normal sort, becomes an ordered array. No longer has the nature of the heap.

Boom, the code will be pasted later.

"Algorithm learning" old algorithm, new posture, stl--heap

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.