sort_heap

轉換堆疊為已排序的範圍。

template<class RandomAccessIterator>
   void sort_heap(
      RandomAccessIterator _First, 
      RandomAccessIterator _Last
   );
template<class RandomAccessIterator, class Predicate>
   void sort_heap(
      RandomAccessIterator _First, 
      RandomAccessIterator _Last,
      Predicate _Comp
   );

參數

  • _First
    解決的隨機存取 Iterator 的第一個項目位置在目標堆積。

  • _Last
    解決的隨機存取 Iterator 超過最後一個項目的位置是在目標堆積。

  • _Comp
    定義感受遠遠之使用者定義的述詞函式物件哪一個項目小於另一個。一個二進位述詞採用兩個引數並傳回 true ,當內容和 false ,則內容。

備註

中有兩個屬性:

  • 第一個項目永遠是最大。

  • 項目在某個時間可能會加入或移除。

在應用程式之後,如果演算法,範圍會套用至不再是堆疊。

,因為對等項目相對順序不一定會保留,這不是穩定的排序。

堆疊是理想的方式實作優先權佇列,並且可用於標準樣板程式庫 (STL) 容器配置器 priority_queue 類別的實作。

參考的範圍必須是有效的,任何指標必須 dereferenceable,並在序列中最後一個位置開始可取得的會增加。

複雜度是 N 記錄 NN = (_Last – _First)。

範例

// alg_sort_heap.cpp
// compile with: /EHsc
#include <algorithm>
#include <functional>
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
using namespace std;

void print(const string& s, const vector<int>& v) {
    cout << s << ": ( ";

    for (auto i = v.begin(); i != v.end(); ++i) {
        cout << *i << " ";
    }

    cout << ")" << endl;
}

int main() {
    vector<int> v;
    for (int i = 1; i <= 9; ++i) {
        v.push_back(i);
    }
    print("Initially", v);

    random_shuffle(v.begin(), v.end());
    print("After random_shuffle", v);

    make_heap(v.begin(), v.end());
    print("     After make_heap", v);

    sort_heap(v.begin(), v.end());
    print("     After sort_heap", v);

    random_shuffle(v.begin(), v.end());
    print("             After random_shuffle", v);

    make_heap(v.begin(), v.end(), greater<int>());
    print("After make_heap with greater<int>", v);

    sort_heap(v.begin(), v.end(), greater<int>());
    print("After sort_heap with greater<int>", v);
}

範例輸出

Initially: ( 1 2 3 4 5 6 7 8 9 )
After random_shuffle: ( 9 2 7 3 1 6 8 4 5 )
     After make_heap: ( 9 5 8 4 1 6 7 2 3 )
     After sort_heap: ( 1 2 3 4 5 6 7 8 9 )
             After random_shuffle: ( 5 8 3 1 2 9 7 6 4 )
After make_heap with greater<int>: ( 1 2 3 4 5 9 7 6 8 )
After sort_heap with greater<int>: ( 9 8 7 6 5 4 3 2 1 )

需求

標題: <algorithm>

命名空間: std

請參閱

參考

heap

標準樣板程式庫