一 概述
C++ 标准库中提供了很多算法,定义于头文件 < algorithm >。本文主要探究以下用于 区间是否构成堆 的算法:
is_heap(C++11) 区间元素是否构成大堆 is_heap_until(C++11) 查找能成为大堆的最大子范围
二 堆
性质
堆中某个节点的值总是不大于或不小于其父节点的值。 堆总是一棵完全二叉树。 分类
三 辅助函数
四 std::is_heap(C++11)
template < class RandomIt >
bool is_heap ( RandomIt first, RandomIt last ) ; ( 1 ) ( C++ 11 起) ( C++ 20 前)
template < class RandomIt >
constexpr bool is_heap ( RandomIt first, RandomIt last ) ; ( 1 ) ( C++ 20 起)
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 前)
template < class RandomIt , class Compare >
constexpr bool is_heap ( RandomIt first, RandomIt last, Compare comp ) ; ( 3 ) ( C++ 20 起)
template < class ExecutionPolicy , class RandomIt , class Compare >
bool is_heap ( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp ) ; ( 4 ) ( C++ 17 起)
说明
默认用 operator< 比较元素。 (3)用给定的二元比较函数 comp 比较元素。
五 std::is_heap_until(C++11)
查找能成为大堆的最大子范围 定义
形式类似 is_heap ,返回值为满足范围的最大元素对应的迭代器
六 Demo
std:: vector< int > vc1{ 3 , 2 , 1 } ;
std:: vector< int > vc2;
fill ( vc2, 1 , 3 ) ;
std:: vector< int > vc3{ 3 , 2 , 1 , 3 , 2 , 1 } ;
print ( "vc1: " , vc1) ;
print ( "vc2: " , vc2) ;
print ( "vc3: " , vc3) ;
std:: cout << "vc1 is "
<< ( std:: is_heap ( vc1. begin ( ) , vc1. end ( ) ) ? "" : "not " )
<< "heap" << std:: endl;
std:: cout << "vc2 is "
<< ( std:: is_heap ( vc2. begin ( ) , vc2. end ( ) ) ? "" : "not " )
<< "heap" << std:: endl;
std:: cout << "vc2 is "
<< ( std:: is_heap ( vc2. begin ( ) , vc2. end ( ) , std:: greater< int > ( ) ) ? "" : "not " )
<< "heap" << std:: endl;
std:: cout << "vc3 is "
<< ( std:: is_heap ( vc3. begin ( ) , vc3. end ( ) ) ? "" : "not " )
<< "heap" << std:: endl;
auto it1 = std:: is_heap_until ( vc1. begin ( ) , vc1. end ( ) ) ;
std:: cout << "until No." << std:: distance ( vc1. begin ( ) , it1)
<< " vc1 is heap" << std:: endl;
auto it2 = std:: is_heap_until ( vc2. begin ( ) , vc2. end ( ) ) ;
std:: cout << "until No." << std:: distance ( vc2. begin ( ) , it2)
<< " vc2 is heap" << std:: endl;
auto it3 = std:: is_heap_until ( vc3. begin ( ) , vc3. end ( ) ) ;
std:: cout << "until No." << std:: distance ( vc3. begin ( ) , it3)
<< " vc3 is heap" << std:: endl;
vc1: 3 2 1
vc2: 1 2 3
vc3: 3 2 1 3 2 1
vc1 is heap
vc2 is not heap
vc2 is heap
vc3 is not heap
until No. 3 vc1 is heap
until No. 1 vc2 is heap
until No. 3 vc3 is heap
说明
结果1, v2为小堆,因为 comp 为 greater, 所以 is_heap返回真。
七 参考