C++標準模板庫中的std::is_heap()函數用於檢查給定範圍的元素是否形成Max Heap。當給定範圍的元素形成Max Heap時,它返回True,否則返回False。
頭文件:
#include <algorithm>
用法:
is_heap(first, last)
參數:它有兩個參數,迭代器指向範圍的第一個和最後一個元素。
返回值:該函數返回以下值:
- True:如果[first,last)範圍內的元素形成最大堆。
- False:如果[first,last)範圍內的元素沒有形成最大堆。
下麵是說明std::is_heap()的程序:
程序1:
// C++ program to illustrate
// the std::is_heap()
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Driver Code
int main()
{
// Given list of numbers
vector<int> arr = { 3, 1, 5, 1, 9, 8 };
// Check if arr[] forms max-heap or not
bool isHeap = is_heap(arr.begin(),
arr.end());
if (isHeap) {
cout << "Forms a Max Heap";
}
else {
cout << "Doesn't forms a Max Heap";
}
}
輸出:
Doesn't forms a Max Heap
程序2:
// C++ program to illustrate the std::is_heap()
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Driver Code
int main()
{
// Given list of numbers
vector<int> arr = { 3, 1, 5, 1, 9, 8 };
// Check if arr[] forms max-heap or not
bool isHeap = is_heap(arr.begin(),
arr.end());
// isHeap is false then make Max Heap
// using in built function make_heap
if (!isHeap) {
make_heap(arr.begin(), arr.end());
}
// Else already a heap
else {
cout << "Already Max Heap\n";
}
// Print all the elements of arr
// after make Max Heap
for (auto& it:arr) {
cout << it << ' ';
}
return 0;
}
輸出:
9 3 8 1 1 5
參考: http://www.cplusplus.com/reference/algorithm/is_heap/
相關用法
- C++ cin get()用法及代碼示例
- C++ std::less用法及代碼示例
- C++ std::add_lvalue_reference用法及代碼示例
- C++ std::greater用法及代碼示例
- C++ std::is_nothrow_constructible用法及代碼示例
- C++ std::is_trivially_move_constructible用法及代碼示例
- C++ std::is_trivially_move_assignable用法及代碼示例
- C++ std::is_nothrow_copy_constructible用法及代碼示例
- C++ std::make_signed用法及代碼示例
- C++ std::rank用法及代碼示例
- C++ std::is_nothrow_assignable用法及代碼示例
- C++ cauchy_distribution a()用法及代碼示例
- C++ ratio_equal()用法及代碼示例
- C++ std::to_address用法及代碼示例
- C++ std::is_trivially_assignable用法及代碼示例
- C++ std::remove_const用法及代碼示例
- C++ std::is_nothrow_destructible用法及代碼示例
- C++ std::remove_volatile用法及代碼示例
- C++ std::equal_to用法及代碼示例
注:本文由純淨天空篩選整理自kivi大神的英文原創作品 std::is_heap() in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。