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

© . All rights reserved.