◐ Shell
clean mode source ↗

std::push_heap - cppreference.com

提供: cppreference.com

<tbody> </tbody> <tbody class="t-dcl-rev t-dcl-rev-num "> </tbody><tbody> </tbody> <tbody class="t-dcl-rev t-dcl-rev-num "> </tbody><tbody> </tbody>

ヘッダ <algorithm> で定義

(1)

template< class RandomIt > void push_heap( RandomIt first, RandomIt last );

(C++20未満)

template< class RandomIt > constexpr void push_heap( RandomIt first, RandomIt last );

(C++20以上)
(2)

template< class RandomIt, class Compare > void push_heap( RandomIt first, RandomIt last, Compare comp );

(C++20未満)

template< class RandomIt, class Compare > constexpr void push_heap( RandomIt first, RandomIt last, Compare comp );

(C++20以上)

範囲 [first, last-1) によって定義される最大ヒープに位置 last-1 の要素を挿入します。 1つめのバージョンは要素を比較するために operator< を使用し、2つめのバージョンは指定された比較関数 comp を使用します。

引数

first, last - 変更するヒープを定義する要素の範囲
comp - 第1引数が第2引数より小さい場合に true を返す、比較関数オブジェクト (Compare の要件を満たすオブジェクト)。

比較関数のシグネチャは以下と同等であるべきです。

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

シグネチャが const & を持つ必要はありませんが、関数は渡されたオブジェクトを変更してはならず、値カテゴリに関わらず Type1 および Type2 型 (およびそれらの const 修飾された型) のすべての値を受理できなければなりません (そのため Type1 & は許されません。 また Type1 に対してムーブがコピーと同等でなければ Type1 も許されません (C++11以上))。
Type1 および Type2 は、どちらも RandomIt 型のオブジェクトの逆参照から暗黙に変換可能なものでなければなりません。 ​

型の要件
-RandomItLegacyRandomAccessIterator の要件を満たさなければなりません。
-RandomIt を逆参照した型は MoveAssignable および MoveConstructible の要件を満たさなければなりません。

戻り値

(なし)

計算量

多くとも log(N) 回の比較、ただし N=std::distance(first, last) です。

ノート

最大ヒープは以下の性質を持つ要素の範囲 [f,l) です。

  • N = l - f としたとき、すべての 0 < i < N について f[floor(
    i-1
    2
    )]
    f[i] より小さくない。
  • std::push_heap() を使用して新しい要素を追加できる。
  • std::pop_heap() を使用して最初の要素を削除できる。

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> v { 3, 1, 4, 1, 5, 9 };

    std::make_heap(v.begin(), v.end());

    std::cout << "v: ";
    for (auto i : v) std::cout << i << ' ';
    std::cout << '\n';

    v.push_back(6);

    std::cout << "before push_heap: ";
    for (auto i : v) std::cout << i << ' ';
    std::cout << '\n';

    std::push_heap(v.begin(), v.end());

    std::cout << "after push_heap: ";
    for (auto i : v) std::cout << i << ' ';
    std::cout << '\n';
}

出力:

v: 9 5 4 1 1 3 
before push_heap: 9 5 4 1 1 3 6 
after push_heap:  9 5 6 1 1 3 4

関連項目