c 的STL中堆的運用

2021-08-15 02:46:10 字數 1306 閱讀 7483

stl中的建立的隊預設是最大堆,要想用最小堆的話,必須要在push_heap,pop_heap,make_heap等每乙個函式後面加第三個引數greater(),括號不能省略

make_heap(_first, _last, _comp); //預設是建立最大堆的。對int型別,可以在第三個引數傳入greater()得到最小堆。

push_heap (_first, _last); //在堆中新增資料,要先在容器中加入資料,再呼叫push_heap ()

pop_heap(_first, _last); //在堆中刪除資料,要先呼叫pop_heap()再在容器中刪除資料

sort_heap(_first, _last); //堆排序,排序之後就不再是乙個合法的heap了

//堆的基本操作舉例

#include #include #include using namespace std;

int main () ;

vectorv(a, a + sizeof(a)/sizeof(a[0]));

make_heap(v.begin(),v.end());

cout << "initial max of heap : " << v.front() << endl;

pop_heap(v.begin(),v.end()); v.pop_back();

cout << "max of heap after pop : " << v.front() << endl;

v.push_back(7); push_heap(v.begin(),v.end());

cout << "max of heap after push: " << v.front() << endl;

sort_heap (v.begin(),v.end());

cout << "sorted range :";

for (unsigned i=0; i#include #include #include #include #include using namespace std;

vectorgetleastnumbers_solution(vectorinput, int k)

return v;

} int main()

vectorq = getleastnumbers_solution(v, 2);

for(int i = 0; i < q.size(); ++i)

return 0;

}

STL 中 remove 的運用

by a code rabbit 今天在看別人的解題報告時,發現這麼一行 remove pack 0 pack strlen pack 0 刪除行中的空格頓時想起前幾天寫的乙個函式 void filterspaces char expression new,char expression pos e...

STL中的堆操作

堆在我們做演算法時應該有映像吧,分為大根堆,小根堆。stl中的其實是對堆有實現的,使得我們可以直接拿來用。相關的函式是make heap push heap pop heap sort heap make heap make heap first,end,cmp 引數有3個,第乙個為堆建立堆的第乙個...

關於STL中堆的建立

最近總有新手要問堆怎麼寫,我是這麼想的 既然都學c 了,堆這種東西怎麼能手寫呢,太對不起stl了 當然能手寫的都是的大神了,這只是我懶得手打的理由 正好之前機房有位大神將他學習的堆教給了我 我就以他講的寫一篇blog來幫助其他人吧 這裡先介紹一下vector vector是乙個動態陣列 當你需要多少...