在线文档教程
C++
算法 | Algorithm

std::make_heap

STD:使[医]堆

Defined in header
template< class RandomIt > void make_heap( RandomIt first, RandomIt last (1)
template< class RandomIt, class Compare > void make_heap( RandomIt first, RandomIt last, Compare comp (2)

构造一个最大堆在范围内[first, last)函数的第一个版本使用operator<为了比较元素,第二个函数使用给定的比较函数。comp...

参数

first, last-the range of elements to make the heap from
comp-comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b The signature does not need to have const &, but the function object must not modify the objects passed to it. The types Type1 and Type2 must be such that an object of type RandomIt can be dereferenced and then implicitly converted to both of them. ​

类型要求

---它必须符合RandomAccessIterator的要求。

-取消引用的随机数的类型必须符合可移动分配和移动可建的要求。

返回值

%280%29

复杂性

顶多3*std::distance(first, last)比较。

注记

最大堆是一系列元素[f,l)具有以下属性:

  • 带着N = l - f,为所有人0 < i < N,,,f[floor(i-12)]比不上f[i]...

  • 可以使用std::push_heap()

  • 第一个元素可以使用std::pop_heap()

二次

#include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v { 3, 1, 4, 1, 5, 9 }; std::cout << "initially, v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; std::make_heap(v.begin(), v.end() std::cout << "after make_heap, v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; std::pop_heap(v.begin(), v.end() auto largest = v.back( v.pop_back( std::cout << "largest element: " << largest << '\n'; std::cout << "after removing the largest element, v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; }

二次

产出:

二次

initially, v: 3 1 4 1 5 9 after make_heap, v: 9 5 4 1 1 3 largest element: 9 after removing the largest element, v: 5 3 4 1 1

二次

另见

sort_heapturns a max heap into a range of elements sorted in ascending order (function template)
priority_queueadapts a container to provide priority queue (class template)
greaterfunction object implementing x > y (class template)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/Algorithm/make[医]堆