有的時候為了維護數據,我們使用stl的堆去維護一序列。
首先您要弄清楚堆和棧的區別,即heap和stack
stl中的堆默認是最大堆。
先介紹 push_heap,pop_heap,make_heap,sort_heap這四個算法,這四個不是C++11新增加的內容。
首先是如何產生一個最大推:
make_heap
原型:
template
void make_heap (RandomAccessIterator first, RandomAccessIterator last);
template
void make_heap (RandomAccessIterator first, RandomAccessIterator last,
Compare comp );
第一個就是默認的,最大堆。
作用:
Rearranges the elements in the range [first,last) in such a way that they form a heap.
push_heap,pop_heap
這兩個就不再贅述,在代碼裡有顯現。
sort_heap
Sort elements of heap
看一段上面四個方法的應用:
#include // std::cout
#include // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include // std::vector
int main() {
int myints[] = { 10,20,30,5,15 };
std::vector v(myints, myints + 5);
std::make_heap(v.begin(), v.end());
std::cout << "initial max heap : " << v.front() << '\n';
std::pop_heap(v.begin(), v.end());
v.pop_back();
std::cout << "max heap after pop : " << v.front() << '\n';
v.push_back(99);
std::push_heap(v.begin(), v.end());
std::cout << "max heap after push: " << v.front() << '\n';
std::sort_heap(v.begin(), v.end());
std::cout << "final sorted range :";
for (unsigned i = 0; i<v.size(); i++)="" std::cout="" <<="" '="" v[i];="" '\n';="" return="" 0;="" }="" 輸出:="" initial="" max="" heap="" :="" 30="" after="" pop="" 20="" push="" 99="" final="" sorted="" range="" 5="" 10="" 15="" 99
接下來看看在上面的基礎上,C++11又新增加了哪些內容:
is_heap
作用:
Returns true if the range [first,last) forms a heap, as if constructed with make_heap.
應用:
#include // std::cout
#include // std::is_heap, std::make_heap, std::pop_heap
#include // std::vector
int main () {
std::vector foo {9,5,2,6,4,1,3,8,7};
if (!std::is_heap(foo.begin(),foo.end()))
std::make_heap(foo.begin(),foo.end());
std::cout << "Popping out elements:";
while (!foo.empty()) {
std::pop_heap(foo.begin(),foo.end()); // moves largest element to back
std::cout << ' ' << foo.back(); // prints back
foo.pop_back(); // pops element out of container
}
std::cout << '\n';
return 0;
}
is_heap_until
作用:
Find first element not in heap order
Returns an iterator to the first element in the range [first,last) which is not in a valid position if the range is considered a heap (as if constructed with make_heap).
應用:
#include // std::cout
#include // std::is_heap_until, std::sort, std::reverse
#include // std::vector
int main () {
std::vector foo {2,6,9,3,8,4,5,1,7};
std::sort(foo.begin(),foo.end());
std::reverse(foo.begin(),foo.end());
auto last = std::is_heap_until (foo.begin(),foo.end());
std::cout << "The " << (last-foo.begin()) << " first elements are a valid heap:";
for (auto it=foo.begin(); it!=last; ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
注:例子來源於www.cplusplus.com網站