C++ STL 中的堆 - make_heap()、push_heap()、pop_heap()、sort_heap()、is_heap、is_heap_until()
pythonserver side programmingprogramming更新于 2025/10/17 8:44:17
在本节中,我们将看到 C++ STL 中存在的堆数据结构。这允许更快地将数字输入到堆中,并且每次检索数字时总是会产生最大的数字,即每次弹出剩余数字中的最大数字。堆的其他元素的排列取决于实现。堆操作如下 −
make_heap() − 这会将容器中的范围转换为堆。
front() −这将返回堆中最大的第一个元素。
示例
让我们看看下面的实现方式更好地理解 −
#include; 使用命名空间 std; int main() { 向量<int>堆 = {33, 43, 53, 38, 28}; make_heap(heap.begin(), heap.end()); cout <<"顶部元素是:" << heap.front() <<结束; }
输出
顶部元素为: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 <<"顶部元素为:<< heap.front() << endl;
heap.push_back(60);
push_heap(heap.begin(), heap.end());
cout <<"插入后顶部元素:<<< heap.front() << endl;
pop_heap(heap.begin(), heap.end());
heap.pop_back();
cout <<"删除后顶部元素:<<< heap.front() << endl;
}
输出
顶部元素为:53 插入后顶部元素:60 删除后顶部元素: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 <<"排序前 : ";
for (const auto &i : heap) {
cout << i << ' ';
}
sort_heap(heap.begin(), heap.end());
cout <<"\n排序后 : ";
for (const auto &i : heap) {
cout << i << ' ';
}
}
输出
排序前 : 53 43 33 38 28 排序后 : 28 33 38 43 53
is_heap() −这用于检查容器是否为堆。在大多数实现中,反向排序的容器被视为堆。当容器为堆时,此函数返回 true heap,否则返回 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 <<"这是一个堆": cout <<"这不是堆";
cout << endl;
cout < "Heapify" << endl;
make_heap(heap.begin(), heap.end());
is_heap(heap.begin(), heap.end()) ? cout <<"这是一个堆": cout <<"这不是堆";
cout << endl;
vector<int>::iterator iter2 = is_heap_until(heap.begin(), heap.end());
cout <<"堆元素为:";
for (iter=heap.begin(); iter!=iter2; iter++)
cout << *iter <<" ";
}
输出
这不是堆 Heapify 这是一个堆 堆元素为:53 43 33 38 28
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

