名稱空間
變體
操作

std::pop_heap

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

將位置 first 處的值與位置 last - 1 處的值進行交換,並將子範圍 [firstlast - 1) 轉換為堆。這使得 [firstlast) 中的第一個元素被移除。

1) [firstlast) 是關於 operator<(C++20 前)std::less{}(C++20 起) 的堆。
2) [firstlast) 是關於 comp 的堆。

如果滿足以下任何條件,則行為是未定義的:

  • [firstlast) 為空。
  • [firstlast) 不是關於相應比較器的堆。
(C++11 前)
(C++11 起)

目錄

[編輯] 引數

first, last - 定義要修改(提取根元素)的非空二叉堆元素的 範圍 的迭代器對。
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 的要求。

[編輯] 複雜度

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

1) 最多 2log(N) 次比較,使用 operator<(C++20 前)std::less{}(C++20 起)
2) 最多 2log(N) 次應用比較函式 comp

[編輯] 示例

#include <algorithm>
#include <iostream>
#include <string_view>
#include <type_traits>
#include <vector>
 
void println(std::string_view rem, const auto& v)
{
    std::cout << rem;
    if constexpr (std::is_scalar_v<std::decay_t<decltype(v)>>)
        std::cout << v;
    else
        for (int e : v)
            std::cout << e << ' ';
    std::cout << '\n';
}
 
int main()
{
    std::vector<int> v{3, 1, 4, 1, 5, 9};
 
    std::make_heap(v.begin(), v.end());
    println("after make_heap: ", v);
 
    std::pop_heap(v.begin(), v.end()); // moves the largest to the end
    println("after pop_heap:  ", v);
 
    int largest = v.back();
    println("largest element: ", largest);
 
    v.pop_back(); // actually removes the largest element
    println("after pop_back:  ", v);
}

輸出

after make_heap: 9 5 4 1 1 3
after pop_heap:  5 3 4 1 1 9
largest element: 9
after pop_back:  5 3 4 1 1

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 1205 C++98 如果 [firstlast) 為空,則行為不明確 在這種情況下行為未定義

[編輯] 參閱

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