[問題] std::make_heap 資料的排序問題

看板C_and_CPP作者 (我一個人)時間9年前 (2016/07/03 15:08), 編輯推噓2(201)
留言3則, 3人參與, 最新討論串1/1
最近在研究C++標準看到make_heap的範例用法。 連結: http://en.cppreference.com/w/cpp/algorithm/make_heap #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v { 3, 1, 4, 1, 5, 9 }; std::cout << "initially, v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; std::make_heap(v.begin(), v.end()); std::cout << "after make_heap, v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; std::pop_heap(v.begin(), v.end()); auto largest = v.back(); v.pop_back(); std::cout << "largest element: " << largest << '\n'; std::cout << "after removing the largest element, v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; } 網站直接Run Code運行結果: initially, v: 3 1 4 1 5 9 after make_heap, v: 9 5 4 1 1 3 largest element: 9 after removing the largest element, v: 5 3 4 1 1 覺得很奇怪的地方是,範例中排序的結果怪怪的。 after make_heap, v: 9 5 4 1 1 3 應該是 9 5 4 3 1 1才對吧? 自己又用VC2015運行一次,發現結果一樣 是我哪邊誤解了嗎?? 懇請解答~ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.177.14.201 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1467558507.A.6D5.html

07/03 23:26, , 1F
我大概知道為什麼了 謝謝 因為裡面是max heap結構
07/03 23:26, 1F

07/04 11:22, , 2F
你可以傳入compare function
07/04 11:22, 2F

07/07 13:18, , 3F
建議用priority queue
07/07 13:18, 3F
文章代碼(AID): #1NUIfhRL (C_and_CPP)