c++ STL heap的构造

数据排列方式:堆

c++中堆只是一种数据排列方式
只能用于vector容器;
基于完全二叉树,(最底层叶子节点都在最左边)
头文件 algorithm;
用 make_heap(iterator start,iterator end)实现

#include <vector>
#include <string>
#include <iostream>
#include <list>
#include <iterator>
#include <deque>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
int main()
{

    vector<int> a{2,3,6,4,7,9,41,43,31};
    make_heap(a.begin(),a.end());   //默认为降序(即 大根堆)
    for(auto tmp:a)
        cout << tmp <<",";      // 43,31,41,4,7,9,6,2,3,
    cout << endl;

    make_heap(a.begin(),a.end(),less<int> ());  //降序堆
    for(auto tmp:a)
        cout << tmp <<",";      // 43,31,41,4,7,9,6,2,3,
    cout << endl;

    make_heap(a.begin(),a.end(),greater<int> ());  //升序堆
    for(auto tmp:a)
        cout << tmp <<",";      // 2,3,6,4,7,9,41,43,31,
    cout << endl;

    //push_heap()   将最后一位的值插入堆中,使数据依然是堆,成堆方式必须与make_heap()时相同
    a.push_back(1);
    push_heap(a.begin(),a.end(),greater<int> ());
    for(auto tmp:a)
        cout << tmp <<",";      // 1,2,6,4,3,9,41,43,31,7
    cout << endl;
    //push_heap中的_Compare和make_heap中的_Compare参数必须是一致的,不然会插入堆失败,最后一个元素还是在最后位置,导致插入失败

    //pop_heap()   将堆顶元素(即为数组第一个位置)和数组最后一个位置对调,然后使前n-1位依然成堆
    pop_heap(a.begin(),a.end(),greater<int>());
    for(auto tmp:a)
        cout << tmp <<",";      // 2,3,6,4,7,9,41,43,31,1,
    cout << endl;
    a.pop_back();


//    list<int> b{2,3,6,4,7,9,41,43,31};        //error  make_heap只能用在vector上
//    make_heap(b.begin(),b.end());
//    for(auto tmp:b)
//        cout << tmp <<",";
//    cout << endl;

//    deque<int> c{2,3,6,4,7,9,41,43,31};       //error
//    make_heap(c.begin(),c.end());
//    for(auto tmp:c)
//        cout << tmp <<",";
//    cout << endl;

    return 0;

}

在这里插入图片描述
默认为大根堆

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值