📜  C++ STL 中的堆 | make_heap()、push_heap()、pop_heap()、sort_heap()、is_heap、is_heap_until()(1)

📅  最后修改于: 2023-12-03 15:13:55.037000             🧑  作者: Mango

C++ STL 中的堆

堆是一种数据结构,常用于动态维护数据的最值。C++ STL 中提供了多个堆相关的函数,包括 make_heap()push_heap()pop_heap()sort_heap()is_heap()is_heap_until()

make_heap()

make_heap() 可以将一个序列转换为堆:

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> nums = {3, 1, 4, 1, 5, 9};
    std::make_heap(nums.begin(), nums.end());
    return 0;
}

此时,nums 已经是一个堆了。可以用 std::is_heap() 来检查:

bool is_heap = std::is_heap(nums.begin(), nums.end());
push_heap()

push_heap() 可以向堆中加入一个元素:

nums.push_back(2);
std::push_heap(nums.begin(), nums.end());

此时,nums 成为了 {9, 5, 4, 3, 2, 1, 1, 2},其中前半部分 {9, 5, 4, 3, 2} 是堆。

pop_heap()

pop_heap() 可以把堆顶的元素取出(不删除)并放到序列的末尾:

std::pop_heap(nums.begin(), nums.end());  // 把 9 取出

此时,nums 成为了 {2, 5, 4, 3, 1, 1, 2, 9},其中前半部分 {2, 5, 4, 3, 1, 1, 2} 是堆。

sort_heap()

sort_heap() 可以按照堆排序的顺序将堆中的元素排序:

std::sort_heap(nums.begin(), nums.end());  // 排序为 {1, 1, 2, 2, 3, 4, 5, 9}
is_heap()

is_heap() 可以判断一个序列是否是堆:

bool is_heap = std::is_heap(nums.begin(), nums.end());
is_heap_until()

is_heap_until() 可以找到序列中第一个不满足堆条件的位置:

auto it = std::is_heap_until(nums.begin(), nums.end());
if (it != nums.end()) {
    std::cout << "第一个不满足堆条件的位置是:" << std::distance(nums.begin(), it) << '\n';
}

以上就是 C++ STL 中堆相关函数的介绍。