C++ 堆

C++ 堆

1、 堆

1.1 定义

堆(heaps)是一种特殊的二叉树,STL 中的priority_queue 容器适配器底层就是采用堆来组织数据存储的。

用来创建堆的函数定义在头文件 <algorithm> 中,max_heap() 对随机访问迭代器指定的一段元素重新排列,生成一个堆。默认使用的是<运算符,可以生成一个大顶堆。例如:

    # c++
    vector<int> min= {2, 10, 3, 7, 8, 12, 1, 6};
    make_heap(min.begin(), min.end(), greater<>());
    printHeap(min); //1 6 2 7 8 12 3 10   
    min.push_back(4); // 
    printHeap(min); //1 6 2 7 8 12 3 10 4  
    push_heap(min.begin(), min.end(), greater<>());
    printHeap(min); //1 4 2 6 8 12 3 10 7   
    
    # python
    heap = [2, 10, 3, 7, 8, 12, 1, 6]
	heapify(heap) # [1, 6, 2, 7, 8, 12, 3, 10]
	heappush(heap, 0) # [0, 1, 2, 6, 8, 12, 3, 10, 7]
	print(heappop(heap)) # 0 heap: [1, 6, 2, 7, 8, 12, 3, 10]
#include <iostream> 
#include <algorithm> 
#include <list>
#include <queue>
using namespace std; 

#include <iomanip>
using std::setw;

void printHeap(vector<int> &v){
    for(vector<int>::iterator it= v.begin();it!=v.end();++it){
        cout<< *it <<" ";
    }
    cout<<"\n"<<endl;
}

int main(){   
    vector<int> min= {10,30,22,6,15,9};
    make_heap(min.begin(), min.end(), greater<>());
    printHeap(min); //6 10 9 30 15 22 20   仍为小顶堆
    // queue<int>a;
    priority_queue<int>a;
    // priority_queue<int,vector<int>,greater<int> >a;
    int n;
    for(int i=0;i<6;i++){
        a.push(min[i]);
    }
    while(!a.empty()){
        cout<<a.top()<<endl;
        a.pop();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
05-30
C++中的是一种基于完全二叉树的数据结构,常用于实现优先队列等需要动态管理元素优先级的场景。 C++中的分为最大和最小两种,最大的根节点是中最大的元素,最小的根节点是中最小的元素。中的每个节点都比它的子节点大(最大)或小(最小)。 C++中可以使用STL中的priority_queue来实现。priority_queue是一个模板类,使用时需要指定元素类型和比较函数。比较函数可以使用lambda表达式、函数指针等方式进行定义,用于对元素进行比较,以确定元素的优先级。 以下是priority_queue的一些常用操作: 1. push(element):将元素加入中。 2. top():返回顶元素。 3. pop():弹出顶元素。 4. size():返回中元素个数。 5. empty():检查是否为空。 以下是使用最大实现的一个示例代码: ```c++ #include <iostream> #include <queue> using namespace std; int main() { priority_queue<int> maxHeap; // push元素 maxHeap.push(3); maxHeap.push(1); maxHeap.push(4); maxHeap.push(1); maxHeap.push(5); // 访问顶元素 cout << maxHeap.top() << endl; // 输出5 // 弹出顶元素 maxHeap.pop(); cout << maxHeap.top() << endl; // 输出4 // 输出中元素个数 cout << maxHeap.size() << endl; // 输出4 // 检查是否为空 cout << maxHeap.empty() << endl; // 输出0 return 0; } ``` 输出结果为: ``` 5 4 4 0 ``` 需要注意的是,priority_queue实现的是最大,如果需要实现最小,需要自定义比较函数并在priority_queue中传入。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值