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



描述

C++ 函式std::algorithm::is_heap_until() 查詢序列中第一個違反最大堆條件的元素。它使用二元函式進行比較。

宣告

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

C++11

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

引數

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

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

  • comp - 一個接受兩個引數並返回 bool 型別的二元函式。

返回值

返回指向第一個違反最大堆條件的元素的迭代器。如果整個序列都是有效的最大堆,則返回last.

異常

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

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

時間複雜度

線性。

示例

以下示例顯示了 std::algorithm::is_heap_until() 函式的使用方法。

#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'};
   auto result = is_heap_until(v.begin(), v.end());

   cout << char(*result) << " is the first element which "
        << "violates the max heap." << endl;

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

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

   if (result == end(v))
      cout << "Entire range is valid heap." << endl;

   return 0;
}

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

d is the first element which violates the max heap.
Entire range is valid heap.
algorithm.htm
廣告