• 堆其实就是一棵完全二叉树(若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边)。

    父节点总是大于或等于子节点,这种情况下被叫作大顶堆,或者父节点总是小于或等于子节点,这种情况下叫作小顶堆。注意,给定父节点的子节点不一定按顺序排列。

    堆不是容器,而是一种特殊的数据组织方式。

    STL中堆的实现

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <string>
    #include <time.h>
    using namespace std;
    
    
    int main()
    {
        std::vector<double>numbers{ 2.5,10.0,3.5,6.5,8.0,12.0,1.5,6.0 };
        std::make_heap(std::begin(numbers), std::end(numbers));
        //默认使用<运算符,生成大顶堆,Result: 12 10 3.5 6.5 8 2.5 1.5 6
        /*添加元素*/
        numbers.push_back(11); // Result: 12 10 3.5 6.5 8 2.5 1.5 6 11
        std::push_heap(std::begin(numbers), std::end(numbers));//调用push_heap恢复堆顺序
        // Result: 12 11 3. 5 10 8 2. 5 1. 5 6 6. 5
        /*删除最大元素*/
        std::pop_heap(std::begin(numbers), std::end(numbers));//pop_heap将首元素下沉到最后
        //Result: 11 10 3.5 6.5 8 2.5 1.5 6 12
        numbers.pop_back();
        //Result: 11 10 3.5 6.5 8 2.5 1.5 6
        if (std::is_heap(std::begin(numbers), std::end(numbers)))
            std::cout << "Great! We still have a heap.
    ";
        else
            std::cout << "oh bother! We messed up the heap.
    ";
        system("pause");
        return 0;
    }
    View Code
  • 相关阅读:
    软工实践寒假作业(1/2)
    java判断是否为数字
    前端测试工具Cypress
    StringBuffer&StringBuilder
    IO流
    kafka简介
    Python学习笔记10--unittest参数化
    python学习笔记9--日志模块logging
    Python学习笔记9-多线程和多进程
    python学习笔记9-单元测试unittest
  • 原文地址:https://www.cnblogs.com/larry-xia/p/11910323.html
Copyright © 2020-2023  润新知