STL Heap用法

xiaoxiao2021-02-27  153

#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,false std::make_heap(v.begin(), v.end()); //创造heap cout << (std::is_heap(v.begin(), v.end()) ? "true" : "false") << "\n"; //判断是否按照默认predicat排序好的heap,true print(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 } 输出:
转载请注明原文地址: https://www.6miu.com/read-14930.html

最新回复(0)