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