zoukankan      html  css  js  c++  java
  • 温故而知新—heap

    堆:堆不是STL中的容器组件,堆有分为大根堆和小根堆,堆的底层实现可以用优先队列进行实现。底层的容器实际上是一个vector。在C++数据结构中,堆也可用数组来实现。对于使用C++的开发人员来说,stl组件的algorithm.h头文件中提供了一下操错堆的方法。具体的方法如下:

    make_heap(),push_heap(),pop_heap();sort_heap()
    具体示例代码如下:
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    int main(int argc, char *argv[]) {
    	std::cout<<"In this case we'll show the operator of heap"<<std::endl;
    	int iArray[]={1,2,3,4,5,6,7};
    	std::vector<int> myvec(iArray,iArray+7);
    	std::cout<<"show the elements of myvec...."<<std::endl;
    	for(std::vector<int>::iterator it = myvec.begin();it != myvec.end();it++){
    		std::cout<<*it<<" ,";
    	}
    	std::cout<<"
    "<<"now we'll create the heap"<<endl;
    	make_heap(myvec.begin(), myvec.end());
    	for(std::vector<int>::iterator it = myvec.begin();it != myvec.end();it++){
    		std::cout<<*it<<" ,";
    	}
    	std::cout<<"
    "<<"now we'll pop the element...."<<std::endl;
    	pop_heap(myvec.begin(), myvec.end());
    	myvec.pop_back();
    	for(std::vector<int>::iterator it = myvec.begin();it != myvec.end();it++){
    		std::cout<<*it<<" ,";
    	}
    	std::cout<<"
    "<<"now we'll push the element...."<<std::endl;
    	myvec.push_back(123);
    	push_heap(myvec.begin(), myvec.end());
    	for(std::vector<int>::iterator it = myvec.begin();it != myvec.end();it++){
    		std::cout<<*it<<" ,";
    	}
    	std::cout<<"
    "<<"now we'll sort the element...."<<std::endl;
    	sort_heap(myvec.begin(), myvec.end());
    	for(std::vector<int>::iterator it = myvec.begin();it != myvec.end();it++){
    		std::cout<<*it<<" ,";
    	}
    	std::cout<<"
    "<<"now the example is end...."<<std::endl;
    	return 0;
    }
    

  • 相关阅读:
    FMDB增删查改
    https相关内容
    支付宝、微信支付参考博客
    下标脚本(Swift)
    函数(swift)
    控制流(swift)
    UIView Methods
    oc js 交互
    我和Lua并非一见钟情,我们期待着日久生情(相遇篇)
    与Python Falling In Love_Python跨台阶(面向对象)
  • 原文地址:https://www.cnblogs.com/newzol/p/6596676.html
Copyright © 2011-2022 走看看