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

© . All rights reserved.