Part Heap : Code Translation into C++ (heap.cpp) (#285)

* 添加heap章节C++版本关于heap的相关操作

* 完善C++版本的heap相关操作

* 完善C++版本的heap相关操作

* fix printHeap function
This commit is contained in:
LoneRanger
2023-02-04 14:35:45 +08:00
committed by GitHub
parent a95fe26303
commit 8e9eecd610
3 changed files with 137 additions and 0 deletions

View File

@ -85,7 +85,39 @@ comments: true
=== "C++"
```cpp title="heap.cpp"
/* 初始化堆 */
// 初始化小顶堆
priority_queue<int, vector<int>, greater<int>> minHeap;
// 初始化大顶堆
priority_queue<int, vector<int>, less<int>> maxHeap;
/* 元素入堆 */
maxHeap.push(1);
maxHeap.push(3);
maxHeap.push(2);
maxHeap.push(5);
maxHeap.push(4);
/* 获取堆顶元素 */
int peek = maxHeap.top(); // 5
/* 堆顶元素出堆 */
// 出堆元素会形成一个从大到小的序列
maxHeap.pop(); // 5
maxHeap.pop(); // 4
maxHeap.pop(); // 3
maxHeap.pop(); // 2
maxHeap.pop(); // 1
/* 获取堆大小 */
int size = maxHeap.size();
/* 判断堆是否为空 */
bool isEmpty = maxHeap.empty();
/* 输入列表并建堆 */
vector<int> input{1, 3, 2, 5, 4};
priority_queue<int, vector<int>, greater<int>> minHeap(input.begin(), input.end());
```
=== "Python"