2014-04-06 114 views
1

我有一個模板函數,它的載體,並創建一個堆construct_heap模板類功能

template<class T, class P> void construct_heap (vector <T>& v1, P pred) 
{ 
     make_heap(v1.begin(),v1.end()); 
     sort_heap(v1.begin(),v1.end(),pred); 
} 

這工作得很好升序排列。當我傳入construct_heap(v1,less()); 它打印出正確的數據

但降序排列..它不能很好地工作。我想不通爲什麼..

可能有人請解釋我在做什麼錯在這裏?

謝謝!

也附接的輸出的PIC ..

OUTPUT

+0

您可以嘗試通過你的比較謂詞['STD:make_heap'(http://en.cppreference.com/w/cpp/算法/ make_heap)作爲第三參數。只是說... – WhozCraig

+0

您可以通過將'pred'傳遞給'merge_heap'來避免調用'sort_heap'。這使您的問題得不到解答。但正如@WhozCraig指出的那樣,你可能會傳遞一個錯誤的「pred」。你可以使用'std :: greater',它肯定會工作,因爲你在這裏處理整數。 –

+0

偉大的工作! – psj01

回答

1

用於製造初始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 
+0

「用於創建初始max_heap的謂詞應該與在排序過程中使用的預測相同。」 - 謝謝! – psj01