C++ STL中的堆 - make_heap()、push_heap()、pop_heap()、sort_heap()、is_heap、is_heap_until()


在本节中,我们将了解C++ STL中存在的堆数据结构。它允许更快地将数据输入到堆中,并且每次检索到的数字总是最大的数字,即每次弹出的是剩余数字中最大的数字。堆的其他元素的排列取决于实现方式。堆操作如下:

  • make_heap() − 将容器中的一个范围转换为堆。

  • front() − 返回堆的第一个元素,也就是最大的数字。

示例

让我们来看下面的实现,以便更好地理解:

 在线演示

#include<bits/stdc++.h>
using namespace std;
int main() {
   vector<int> heap = {33, 43, 53, 38, 28};
   make_heap(heap.begin(), heap.end());
   cout <<"Top element is : " << heap.front() << endl;
}

输出

Top element is : 53
  • push_heap() − 在将元素插入堆后,这有助于重新堆化堆。堆的大小增加1。在堆中,新元素被适当地放置。

  • pop_heap() − 在删除堆中最大的元素后,这有助于重新堆化堆。堆的大小减少1。删除元素后,堆元素会相应地重新组织。

示例

让我们来看下面的实现,以便更好地理解:

 在线演示

#include<bits/stdc++.h>
using namespace std;
int main() {
   vector<int> heap = {33, 43, 53, 38, 28};
   make_heap(heap.begin(), heap.end());
   cout <<"Top element is : " << heap.front() << endl;
   heap.push_back(60);
   push_heap(heap.begin(), heap.end());
   cout <<"Top element after insert : " << heap.front() << endl;
   pop_heap(heap.begin(), heap.end());
   heap.pop_back();
   cout <<"Top element after deletion : " << heap.front() << endl;
}

输出

Top element is : 53
Top element after insert : 60
Top element after deletion : 53
  • sort_heap():使用堆排序技术将堆元素按升序排序。

示例 (C++)

让我们来看下面的实现,以便更好地理解:

 在线演示

#include<bits/stdc++.h>
using namespace std;
int main() {
   vector<int> heap = {33, 43, 53, 38, 28};
   make_heap(heap.begin(), heap.end());
   cout <<"Before Sort : ";
   for (const auto &i : heap) {
      cout << i << ' ';
   }
   sort_heap(heap.begin(), heap.end());
   cout <<"\nAfter Sort : ";
   for (const auto &i : heap) {
      cout << i << ' ';
   }
}

输出

Before Sort : 53 43 33 38 28
After Sort : 28 33 38 43 53
  • is_heap() − 用于检查容器是否为堆。在大多数实现中,反向排序的容器被视为堆。当容器为堆时,此函数返回true,否则返回false。

  • is_heap_until() − 用于查找容器为堆的迭代器位置。

示例

让我们来看下面的实现,以便更好地理解:

 在线演示

#include<bits/stdc++.h>
using namespace std;
int main() {
   vector<int> heap = {33, 43, 53, 38, 28};
   vector<int>::iterator iter;
   is_heap(heap.begin(), heap.end()) ? cout <<"The is a heap ": cout <<"The is not a heap";
   cout << endl;
   cout < "Heapify" << endl;
   make_heap(heap.begin(), heap.end());
   is_heap(heap.begin(), heap.end()) ? cout <<"The is a heap ": cout <<"The is not a heap";
   cout << endl;
   vector<int>::iterator iter2 = is_heap_until(heap.begin(), heap.end());
   cout <<"The heap elements are : ";
   for (iter=heap.begin(); iter!=iter2; iter++)
      cout << *iter <<" ";
}

输出

The is not a heap
Heapify
The is a heap
The heap elements are : 53 43 33 38 28

更新于:2020年8月27日

1K+ 浏览量

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.