C++ 演算法庫 - is_heap() 函式



描述

C++ 函式std::algorithm::is_heap() 測試給定序列是否為最大堆。它使用運算子<進行比較。

宣告

以下是來自 std::algorithm 標頭檔案的 std::algorithm::is_heap() 函式宣告。

C++11

template <class RandomAccessIterator>
bool is_heap(RandomAccessIterator first, RandomAccessIterator last);

引數

  • first − 指向初始位置的隨機訪問迭代器。

  • last − 指向最終位置的隨機訪問迭代器。

返回值

如果給定序列是最大堆,則返回 true;否則返回 false。

異常

如果元素比較或迭代器上的操作丟擲異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

時間複雜度

線性。

示例

以下示例演示了 std::algorithm::is_heap() 函式的使用。

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

using namespace std;

int main(void) {
   vector<int> v = {3, 5, 2, 1, 4};
   bool result;

   result = is_heap(v.begin(), v.end());

   if (result == false)
      cout << "Given sequence is not a max heap." << endl;

   v = {5, 4, 3, 2, 1};

   result = is_heap(v.begin(), v.end());

   if (result == true)
      cout << "Given sequence is a max heap." << endl;
}

讓我們編譯並執行上述程式,這將產生以下結果:

Given sequence is not a max heap.
Given sequence is a max heap.
algorithm.htm
廣告