函式模板
<algorithm>

std::is_heap

預設 (1)
template <class RandomAccessIterator>  bool is_heap (RandomAccessIterator first, RandomAccessIterator last);
自定義 (2)
template <class RandomAccessIterator, class Compare>  bool is_heap (RandomAccessIterator first, RandomAccessIterator last,                Compare comp);
測試範圍是否為堆
如果範圍 [first,last) 構成一個 (如同使用 make_heap 構建的一樣),則返回 true

元素使用第一個版本的 operator< 進行比較,第二個版本使用 comp 進行比較。

引數

first, last
隨機訪問迭代器,指向序列的初始和最終位置。要檢查的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
comp
二元函式,接受範圍內的兩個元素作為引數,並返回一個可轉換為 bool 的值。返回的值指示第一個引數中的元素在它定義的特定嚴格弱序中是否被認為排在第二個引數之前。
該函式不得修改其任何引數。
這可以是指標函式,也可以是函式物件。

返回值

如果範圍 [first,last) 是一個(如同使用 make_heap 構建的一樣),則返回 true,否則返回 false

如果範圍 [first,last) 包含的元素少於兩個,則函式始終返回 true

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// is_heap example
#include <iostream>     // std::cout
#include <algorithm>    // std::is_heap, std::make_heap, std::pop_heap
#include <vector>       // std::vector

int main () {
  std::vector<int> foo {9,5,2,6,4,1,3,8,7};

  if (!std::is_heap(foo.begin(),foo.end()))
    std::make_heap(foo.begin(),foo.end());

  std::cout << "Popping out elements:";
  while (!foo.empty()) {
    std::pop_heap(foo.begin(),foo.end());   // moves largest element to back
    std::cout << ' ' << foo.back();         // prints back
    foo.pop_back();                         // pops element out of container
  }
  std::cout << '\n';

  return 0;
}

輸出
Popping out elements: 9 8 7 6 5 4 3 2 1


複雜度

最多線性於 firstlast 之間距離減一:比較元素對,直到找到不匹配為止。

資料競爭

訪問範圍 [first,last) 中的物件。

異常

如果元素比較或迭代器操作引發異常,則丟擲。
請注意,無效引數會導致未定義行為

另見