STL Heap用法

来源:互联网 发布:淘宝订单不付钱 编辑:程序博客网 时间:2024/06/15 22:41
#include <iostream>#include <iterator>#include <vector>#include <algorithm>#include <string>using namespace std;void print(const vector<int>& v,string info){cout << info << ":";std::copy(v.begin(), v.end(), std::ostream_iterator<int>(cout, ",")); cout << "\n";}void main(){//就排序而言,heap是一种特殊的元素组织方式,应用于heap排序法;heap可被视为一个以序列式集合形成的二叉树//heap的第一个元素总是最大,且能在对数时间内增加或者删除一个元素vector<int> v{3,2,4,1,5};cout << (std::is_heap(v.begin(), v.end()) ? "true" : "false") << "\n";  //判断是否按照默认predicat排序好的heap,falsestd::make_heap(v.begin(), v.end());//创造heapcout << (std::is_heap(v.begin(), v.end()) ? "true" : "false") << "\n";  //判断是否按照默认predicat排序好的heap,trueprint(v,"make");std::pop_heap(v.begin(), v.end()); v.pop_back();//弹出heap中第一个元素print(v,"pop");v.push_back(9); std::push_heap(v.begin(), v.end());//放入一个元素到heap中print(v,"push");std::sort_heap(v.begin(), v.end());//将heap转化为有序序列(此时[beg,end)区间不再是heap)print(v,"sort");cout << (std::is_heap(v.begin(), v.end()) ? "true" : "false") << "\n"; //false}

输出: