【发布时间】:2017-07-31 15:52:14
【问题描述】:
我用 C++ 编写了一个堆实现,今天晚些时候我才知道,C++11 中有内置函数可以使任何基于范围的容器成为堆。
所以出于好奇,我使用自己的实现将向量放入堆中,并使用了函数make_heap(),然后对它们都运行了is_heap()。
使用make_heap() 制作的那个验证为true,但我没有,即使它在技术上是有效的。
源码及截图如下
头文件
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <cmath>
using namespace std;
主堆函数
vector<int> heapify(vector<int> nums, string const & type) {
int n = nums.size();
for (int i = n - 1; i >= 0; i--) {
int parent = floor((i-1)/2);
if (parent >= 0) {
if (type == "min") {
if (nums[i] < nums[parent]) {
swap(nums[i], nums[parent]);
}
} else {
if (nums[i] > nums[parent]) {
swap(nums[i], nums[parent]);
}
}
}
}
return nums;
}
构建堆的函数
vector<int> buildHeap(vector<int> const & nums, string const & type) {
vector<int> heap;
int n = nums.size();
for (int i = 0; i < n; i++) {
heap.push_back(nums[i]);
if (!heap.empty()) {
heap = heapify(heap, type);
}
}
return heap;
}
删除最顶部的元素
int getTop(vector<int> & nums, string const & type) {
int n = nums.size();
if (n < 0) {
throw string("Size of array is less than 0");
} else {
int minElem = nums[0];
swap(nums[0], nums[n-1]);
nums.pop_back();
nums = heapify(nums, type);
return minElem;
}
}
主要功能
int main()
{
vector<int> nums = {45, 56, 78, 89, 21, 38, 6, 67, 112, 45, 3, 1};
vector<int> heap = buildHeap(nums, "min");
for (int num : heap) {
cout << num << " ";
}
cout << "\n";
cout << std::is_heap(nums.begin(), nums.end(), greater<int>()) << "\n";
make_heap(nums.begin(), nums.end(), greater<int>());
for (int num : nums) {
cout << num << " ";
}
cout << "\n";
cout << std::is_heap(nums.begin(), nums.end(), greater<int>()) << "\n";
return 0;
}
控制台输出和https://www.cs.usfca.edu/~galles/visualization/Heap.html 验证的屏幕截图
【问题讨论】:
-
你的谓词被颠倒了
-
在哪里?你能指出我错的源代码或逻辑吗?
-
请重构您发布的代码,以便我可以将其剪切/粘贴到我的 IDE 中。然后我会更新它来告诉你在哪里
-
我绝对不会安装 gcc 来测试你的代码。
-
@deadpoolAlready -- 帮助你的人可能没有 GCC。再次,包括正确的标题。关于为什么不应该使用“bits/stdc++.h”有一个重复的问题。了解实际标题有什么问题?