c++ STL heap的构造

mac2022-06-30  26

数据排列方式:堆

c++中堆只是一种数据排列方式 只能用于vector容器; 基于完全二叉树,(最底层叶子节点都在最左边) 头文件 algorithm; 用 make_heap(iterator start,iterator end)实现

#include <vector> #include <string> #include <iostream> #include <list> #include <iterator> #include <deque> #include <stack> #include <queue> #include <algorithm> using namespace std; int main() { vector<int> a{2,3,6,4,7,9,41,43,31}; make_heap(a.begin(),a.end()); //默认为降序(即 大根堆) for(auto tmp:a) cout << tmp <<","; // 43,31,41,4,7,9,6,2,3, cout << endl; make_heap(a.begin(),a.end(),less<int> ()); //降序堆 for(auto tmp:a) cout << tmp <<","; // 43,31,41,4,7,9,6,2,3, cout << endl; make_heap(a.begin(),a.end(),greater<int> ()); //升序堆 for(auto tmp:a) cout << tmp <<","; // 2,3,6,4,7,9,41,43,31, cout << endl; //push_heap() 将最后一位的值插入堆中,使数据依然是堆,成堆方式必须与make_heap()时相同 a.push_back(1); push_heap(a.begin(),a.end(),greater<int> ()); for(auto tmp:a) cout << tmp <<","; // 1,2,6,4,3,9,41,43,31,7 cout << endl; //push_heap中的_Compare和make_heap中的_Compare参数必须是一致的,不然会插入堆失败,最后一个元素还是在最后位置,导致插入失败 //pop_heap() 将堆顶元素(即为数组第一个位置)和数组最后一个位置对调,然后使前n-1位依然成堆 pop_heap(a.begin(),a.end(),greater<int>()); for(auto tmp:a) cout << tmp <<","; // 2,3,6,4,7,9,41,43,31,1, cout << endl; a.pop_back(); // list<int> b{2,3,6,4,7,9,41,43,31}; //error make_heap只能用在vector上 // make_heap(b.begin(),b.end()); // for(auto tmp:b) // cout << tmp <<","; // cout << endl; // deque<int> c{2,3,6,4,7,9,41,43,31}; //error // make_heap(c.begin(),c.end()); // for(auto tmp:c) // cout << tmp <<","; // cout << endl; return 0; }

默认为大根堆

最新回复(0)