用於製造初始max_heap應該是相同的如排序過程中使用的謂詞的謂詞。與下面的所有隨機訪問容器一起使用的一般解決方案,同時具有向量和雙端隊列。
#include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
#include <random>
template<class T, template<class,class...> class C, class P, class... Args>
void construct_heap(C<T,Args...>& v, const P& pred)
{
std::make_heap(std::begin(v), std::end(v), pred); // <<== same predicate
std::sort_heap(std::begin(v), std::end(v), pred);
}
template<class T, template<class, class...> class C, class... Args>
void print_seq(std::ostream& os, const C<T,Args...>& v)
{
for (auto x : v)
os << x << ' ';
os << '\n';
}
int main()
{
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<> dist(1,99);
std::vector<int> v1;
v1.reserve(25);
std::generate_n(std::back_inserter(v1), v1.capacity(),
[&](){ return dist(rng);});
print_seq(std::cout, v1);
std::deque<int> d1(v1.begin(), v1.end());
print_seq(std::cout, d1);
construct_heap(v1, std::greater<int>());
print_seq(std::cout, v1);
construct_heap(d1, std::greater<int>());
print_seq(std::cout, d1);
return 0;
}
輸出(變化明顯)
16 6 52 81 7 95 72 76 40 68 9 77 66 73 44 7 64 44 3 58 89 24 51 43 26
16 6 52 81 7 95 72 76 40 68 9 77 66 73 44 7 64 44 3 58 89 24 51 43 26
95 89 81 77 76 73 72 68 66 64 58 52 51 44 44 43 40 26 24 16 9 7 7 6 3
95 89 81 77 76 73 72 68 66 64 58 52 51 44 44 43 40 26 24 16 9 7 7 6 3
您可以嘗試通過你的比較謂詞['STD:make_heap'(http://en.cppreference.com/w/cpp/算法/ make_heap)作爲第三參數。只是說... – WhozCraig
您可以通過將'pred'傳遞給'merge_heap'來避免調用'sort_heap'。這使您的問題得不到解答。但正如@WhozCraig指出的那樣,你可能會傳遞一個錯誤的「pred」。你可以使用'std :: greater',它肯定會工作,因爲你在這裏處理整數。 –
偉大的工作! – psj01