标签:也有 vector ret oid 针对 border 用法 fun 特性
要使用less<int>(),以及greater<int>(),请添加头文件#include <functional>,且一定要加括号less<>()
#include<iostream> #include<vector> #include<algorithm> #include <queue> #include <functional> using namespace std; int main(){ vector<int> q; for (int i = 0; i < 10; i++) { q.push_back(i); } make_heap(q.begin(), q.end(),less<int>()); for (int i = 0; i < q.size(); i++) { cout << q[i] << " "; } return 0; }
注意:pop_heap()函数,只是交换了两个数据的位置,如果需要弹出这个数据,请记得在pop_heap()后加上
q.pop_back();
#include<iostream> #include<vector> #include<algorithm> #include <queue> #include <functional> using namespace std; void display(vector<int>q) { for (int i = 0; i < q.size(); i++) { cout << q[i] << " "; } cout << endl; } int main(){ vector<int> q; for (int i = 0; i < 10; i++) { q.push_back(i); } make_heap(q.begin(), q.end(),less<int>()); display(q); pop_heap(q.begin(), q.end(), less<int>()); display(q); return 0; }
在使用push_heap()前,请确保已经把数据通过q.push_back()传入q中,而不是在push_heap()后再使用q.push_back(t)!!
#include<iostream> #include<vector> #include<algorithm> #include <queue> #include <functional> using namespace std; void display(vector<int>q) { for (int i = 0; i < q.size(); i++) { cout << q[i] << " "; } cout << endl; } int main(){ vector<int> q; for (int i = 0; i < 10; i++) { q.push_back(i); } make_heap(q.begin(), q.end(),less<int>()); cout << "插入前" << endl; display(q); q.push_back(12); push_heap(q.begin(), q.end(), less<int>()); cout << "插入后" << endl; display(q); return 0; }
请在使用这个函数前,确定序列符合堆的特性,否则会报错!
#include<iostream> #include<vector> #include<algorithm> #include <queue> #include <functional> using namespace std; void display(vector<int>q) { for (int i = 0; i < q.size(); i++) { cout << q[i] << " "; } cout << endl; } int main(){ vector<int> q; for (int i = 0; i < 10; i++) { q.push_back(i); } make_heap(q.begin(), q.end(),less<int>()); cout << "sort前" << endl; display(q); sort_heap(q.begin(), q.end(), less<int>()); cout << "sort后" << endl; display(q); return 0; }
标签:也有 vector ret oid 针对 border 用法 fun 特性
原文地址:https://www.cnblogs.com/woxiaosade/p/10628388.html