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



描述

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

宣告

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

C++11

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

引數

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

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

  • comp - 一個二元函式,接受兩個引數並返回布林值。

返回值

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

異常

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

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

時間複雜度

線性。

示例

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

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

using namespace std;

bool ignore_case(char a, char b) {
   return (tolower(a) == tolower(b));
}

int main(void) {
   vector<char> v = {'E', 'd', 'C', 'b', 'A'};
   bool result;

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

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

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

   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
廣告