名稱空間
變體
操作

std::is_heap

來自 cppreference.com
< cpp‎ | 演算法
 
 
演算法庫
有約束演算法與針對範圍的演算法 (C++20)
有約束的演算法,例如 ranges::copyranges::sort 等……
執行策略 (C++17)
排序及相關操作
劃分操作
排序操作
二分搜尋操作
(於已劃分範圍上)
集合操作(於已排序範圍上)
歸併操作(於已排序範圍上)
堆操作
is_heap
(C++11)
最小/最大值操作
(C++11)
(C++17)
字典序比較操作
排列操作
C 庫
數值操作
未初始化記憶體上的操作
 
定義於標頭檔案 <algorithm>
template< class RandomIt >
bool is_heap( RandomIt first, RandomIt last );
(1) (C++11 起)
(C++20 起為 constexpr)
template< class ExecutionPolicy, class RandomIt >

bool is_heap( ExecutionPolicy&& policy,

              RandomIt first, RandomIt last );
(2) (C++17 起)
template< class RandomIt, class Compare >
bool is_heap( RandomIt first, RandomIt last, Compare comp );
(3) (C++11 起)
(C++20 起為 constexpr)
template< class ExecutionPolicy, class RandomIt, class Compare >

bool is_heap( ExecutionPolicy&& policy,

              RandomIt first, RandomIt last, Compare comp );
(4) (C++17 起)

檢查 [firstlast) 是否是

1) 檢查堆屬性時使用 operator<(C++20 前)std::less{}(C++20 起)
3) 檢查堆屬性時使用 comp
2,4)(1,3),但按 policy 執行。
僅當滿足所有以下條件時,這些過載才參與過載決議

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>true

(C++20 前)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>true

(C++20 起)

目錄

[編輯] 引數

first, last - 定義要檢查的元素範圍的迭代器對
policy - 要使用的 執行策略
comp - 比較函式物件(即滿足 Compare 要求的物件),如果第一個引數“小於”第二個引數,則返回 true

比較函式的簽名應等效於以下內容

bool cmp(const Type1& a, const Type2& b);

儘管簽名無需具有 const&,但函式不得修改傳遞給它的物件,並且必須能夠接受 Type1Type2 型別的所有值(可能是 const),而不論其值類別(因此,不允許 Type1&,除非 Type1 的移動等同於複製,否則也不允許 Type1(C++11 起))。
型別 Type1Type2 必須使得型別 RandomIt 的物件可以被解引用,然後隱式轉換為兩者。

型別要求
-
RandomIt 必須滿足 LegacyRandomAccessIterator 的要求。
-
Compare 必須滿足 Compare 的要求。

[編輯] 返回值

如果範圍是對應比較器的堆,則為 true,否則為 false

[編輯] 複雜度

給定 N 作為 std::distance(first, last)

1,2) 使用 operator<(C++20 前)std::less{}(C++20 起) 進行 O(N) 次比較。
3,4) 對比較函式 comp 應用 O(N) 次。

[編輯] 異常

帶有模板引數 ExecutionPolicy 的過載按如下方式報告錯誤

  • 如果作為演算法一部分呼叫的函式執行丟擲異常,並且 ExecutionPolicy標準策略之一,則呼叫 std::terminate。對於任何其他 ExecutionPolicy,行為是實現定義的。
  • 如果演算法未能分配記憶體,則丟擲 std::bad_alloc

[編輯] 示例

#include <algorithm>
#include <bit>
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> v{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9};
 
    std::cout << "initially, v:\n";
    for (const auto& i : v)
        std::cout << i << ' ';
    std::cout << '\n';
 
    if (!std::is_heap(v.begin(), v.end()))
    {
        std::cout << "making heap...\n";
        std::make_heap(v.begin(), v.end());
    }
 
    std::cout << "after make_heap, v:\n";
    for (auto t{1U}; const auto& i : v)
        std::cout << i << (std::has_single_bit(++t) ? " | " : " ");
    std::cout << '\n';
}

輸出

initially, v:
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9
making heap...
after make_heap, v:
9 | 6 9 | 5 5 9 7 | 1 1 3 5 8 3 4 2 |

[編輯] 參閱

尋找是一個最大堆的最大子範圍
(函式模板) [編輯]
從一個元素範圍建立一個最大堆
(函式模板) [編輯]
向一個最大堆新增一個元素
(函式模板) [編輯]
從一個最大堆中移除最大的元素
(函式模板) [編輯]
將一個最大堆轉換成一個按升序排序的元素範圍
(函式模板) [編輯]
檢查給定的範圍是否是一個最大堆
(演算法函式物件)[編輯]