zoukankan      html  css  js  c++  java
  • 堆其实就是一棵完全二叉树(若设二叉树的深度为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
  • 相关阅读:
    112、TensorFlow初始化变量
    111、TensorFlow 初始化变量
    110、TensorFlow张量值的计算
    109、TensorFlow计算张量的值
    108、TensorFlow 类型转换
    107、TensorFlow变量(三)
    106、TensorFlow变量 (二) reshape
    105、TensorFlow的变量(一)
    104、Tensorflow 的变量重用
    103、Linux 编译 Kaldi 语音识别工具
  • 原文地址:https://www.cnblogs.com/larry-xia/p/11910323.html
Copyright © 2011-2022 走看看