C++实现堆
2016-06-01 21:24
302 查看
#include <iostream> using namespace std; #include <vector> #include <assert.h> //仿函数 template<class T> struct Less { bool operator()(const T& left, const T& right) { return left < right; } }; template<class T> struct Greater { bool operator()(const T& left, const T& right) { return left > right; } }; template<class T, class Compare = Less<T>>//默认为小堆 class Heap { public: Heap() {} Heap(const T* array, size_t size) { for (size_t i = 0; i < size; ++i) { _a.push_back(array[i]); } for (int i = (_a.size()-2)/2; i >= 0; --i) { _AdjustDown(i); } } void Push(const T& x) { _a.push_back(x); _AdjustUp(_a.size()-1); } void Pop() { assert(!_a.empty()); swap(_a[0], _a[_a.size()-1]); _a.pop_back(); _AdjustDown(0); } T& GetTop() { assert(!_a.empty()); return _a[0]; } bool Empty() { return _a.empty(); } size_t Size() { return _a.size(); } void Print() { for (size_t i = 0; i < _a.size(); ++i) { cout<<_a[i]<<" "; } cout<<endl; } protected: //向下调整 void _AdjustDown(size_t parent) { Compare compare; size_t child = parent*2 + 1; while (child < _a.size()) { //比较左右孩子 if (child+1 < _a.size() && compare(_a[child+1], _a[child])) { ++child; } if (compare(_a[child], _a[parent])) { swap(_a[child], _a[parent]); parent = child; child = parent*2 + 1; } else { break; } } } //向上调整 void _AdjustUp(size_t child) { Compare compare; size_t parent = (child-1)/2; while (child > 0) { if (compare(_a[child], _a[parent])) { swap(_a[parent], _a[child]); child = parent; parent = (child-1)/2; } else { break; } } } protected: vector<T> _a; }; void Test() { int a[10] = {10, 11, 13, 12, 16, 18, 15, 17, 14, 19}; Heap<int, Greater<int>> hp1(a, sizeof(a)/sizeof(a[0])); hp1.Print(); cout<<"size:"<<hp1.Size()<<endl; cout<<"top:"<<hp1.GetTop()<<endl; cout<<"empty:"<<hp1.Empty()<<endl; } int main() { Test(); return 0; }
![](http://s5.51cto.com/wyfs02/M02/82/81/wKioL1dXlTHg6jFPAABaQhYpjXU676.png-wh_500x0-wm_3-wmp_4-s_261171597.png)
本文出自 “zgw285763054” 博客,请务必保留此出处http://zgw285763054.blog.51cto.com/11591804/1785308
相关文章推荐
- C语言练习篇-4河内之塔
- C语言学习篇-6函数、递归、嵌套
- win10下c++通用开发杂记
- c++命名类型转换
- C++中头文件的使用
- c++中的成员访问级别和派生继承方式
- 不使用中间变量交换两数
- sqlite3数据库c语言常用接口应用实例
- HomeWork——Binary Search Tree
- C++ Primer复制控制 13.3 析构函数
- Qt/C++ 继承QWidget setstylesheet解决
- C++独孤九剑第二式——众妙之门(函数处理机制)
- c++-可变参数模板函数
- 队列的使用—WIN32控制台贪吃蛇(VS2010,C++语言)
- 第十三周【项目2 动物这样叫】
- 二叉树的顺序存储结构的C++实现
- VC++学习笔记
- C++ Primer复制控制 13.2 赋值操作符
- C++作业6
- 三种页面置换算法C实现