Namespaces
Variants

std::is_heap

来自 zh.cppreference.net
 
 
算法库
受约束算法及范围算法 (C++20)
受约束算法,例如 ranges::copy、ranges::sort...
排序及相关操作
划分操作
(C++11)    

排序操作
二分搜索操作
(在已划分范围上)
集合操作 (在已排序范围上)
合并操作 (在已排序范围上)
堆操作
最小/最大操作
(C++11)
(C++17)
字典序比较操作
排列操作


 
定义于头文件 <algorithm>
template< class RandomIt >
bool is_heap( RandomIt first, RandomIt last );
(1) (C++11 起)
(C++20 起 constexpr)
template< class ExecutionPolicy, class RandomIt >
bool is_heap( ExecutionPolicy&& policy,
              RandomIt first, RandomIt last );
(2) (C++17 起)
template< class RandomIt, class Compare >
bool is_heap( RandomIt first, RandomIt last, Compare comp );
(3) (C++11 起)
(C++20 起 constexpr)
template< class ExecutionPolicy, class RandomIt, class Compare >
bool is_heap( ExecutionPolicy&& policy,
              RandomIt first, RandomIt last, Compare comp );
(4) (C++17 起)

检查范围 [first, last) 是否为 堆。

1) 相对于 operator<(C++20 前)std::less{}(C++20 起) 检查堆性质。
3) 相对于 comp 检查堆性质。
2,4) 同 (1,3),但按照 policy 执行。
这些重载仅当以下表达式的值为 true 时参与重载决议:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(C++20 前)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(C++20 起)

参数

first, last - 定义待检查元素范围的迭代器对
policy - 要使用的执行策略
comp - 比较函数对象(即满足比较要求对象),当第一个参数小于第二个参数时返回 true 。

比较函数的签名应等价于:

bool cmp ( const Type1 & a, const Type2 & b ) ;

虽然签名不需要包含 const & ,但函数不得修改传递给它的对象,且必须能够接受所有类型(可能为 const 的) Type1 和 Type2 的值,无论其值类别如何(因此不允许使用 Type1 & ,也不允许使用 Type1 ,除非对于 Type1 类型移动操作等同于拷贝操作 (C++11 起) )。
类型 Type1 和 Type2 必须使得 RandomIt 类型的对象在解引用后能隐式转换到这两个类型。

类型要求
-
RandomIt 必须满足 LegacyRandomAccessIterator 的要求。
-
Compare 必须满足 Compare 的要求。

返回值

若该范围相对于相应比较器构成堆,则为 true ;否则为 false 。

复杂度

给定 N 为 std:: distance ( first, last ) :

1,2) O(N) 次比较,使用 operator < (C++20 前) std:: less { } (C++20 起) 。
3,4) O(N) 次比较函数 comp 的应用。

异常

带有名为 ExecutionPolicy 模板形参的重载按以下方式报告错误:

  • 如果作为算法一部分调用的函数执行抛出异常,且 ExecutionPolicy 是某个 标准策略 ,则会调用 std::terminate 。对于任何其他 ExecutionPolicy ,其行为由实现定义。
  • 如果算法无法分配内存,将抛出 std::bad_alloc 。

示例

#include <algorithm>
#include <bit>
#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9};
    std::cout << "初始状态下,v:\n";
    for (const auto& i : v)
        std::cout << i << ' ';
    std::cout << '\n';
    if (!std::is_heap(v.begin(), v.end()))
    {
        std::cout << "正在创建堆...\n";
        std::make_heap(v.begin(), v.end());
    }
    std::cout << "执行 make_heap 后,v:\n";
    for (auto t{1U}; const auto& i : v)
        std::cout << i << (std::has_single_bit(++t) ? " | " : " ");
    std::cout << '\n';
}

输出:

初始状态下,v:
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9
正在创建堆...
执行 make_heap 后,v:
9 | 6 9 | 5 5 9 7 | 1 1 3 5 8 3 4 2 |

参见

查找作为最大堆的最大子范围
(函数模板 & 算法函数对象)
从元素范围中创建一个最大堆
(函数模板 & 算法函数对象)
向最大堆添加一个元素
(函数模板 & 算法函数对象)
从最大堆中移除最大元素
(函数模板 & 算法函数对象)
将最大堆转换为按升序排列的元素范围
(函数模板 & 算法函数对象)
检查给定范围是否为最大堆
(算法函数对象)