转自:chatgpt
1.介绍
std::push_heap
和 std::pop_heap
是 C++ 标准库中用于操作堆(heap)数据结构的算法。这些算法可以帮助你维护一个二叉堆(通常是最小堆或最大堆),使得最大元素或最小元素始终位于容器的开头。二叉堆通常是通过 std::vector
实现的。
std::push_heap
会重新排列容器中的元素,使得最大元素(对于最大堆)或最小元素(对于最小堆)位于容器的开头。时间复杂度为 O(log n),其中 n 是堆的大小。std::pop_heap
将堆中的最大元素(对于最大堆)或最小元素(对于最小堆)移动到容器的末尾,并保持剩余元素的堆属性。并不会直接移除元素,而是将最大或最小元素移到容器的末尾。需要手动调用pop_back()
来移除该元素。std::pop_heap
之后,容器的前 n-1 个元素仍然是一个有效的堆。时间复杂度为 O(log n)。
2.例子
void printVec(const vector<int>& nums)
{
for (int i = 0; i < nums.size(); ++i)
cout << nums[i] << " ";
cout << endl;
}
int main() {
std::vector<int> heap = {10, 20, 30}; // 目前这不是一个堆
std::make_heap(heap.begin(), heap.end()); // 现在这是一个最大堆,默认是大顶堆(less)
printVec(heap); // 30 20 10
heap.push_back(25); // 添加新元素
std::push_heap(heap.begin(), heap.end()); // 维护堆的属性
printVec(heap); // 30 25 10 20
std::pop_heap(heap.begin(), heap.end()); // 最大元素被移到末尾
printVec(heap); // 25 20 10 30
heap.pop_back(); // pop之后剩下的仍然是大顶堆
printVec(heap); // 25 20 10
// 设置小顶堆
make_heap(heap.begin(), heap.end(), greater<int> ()); // greater是小顶堆
printVec(heap); // 10 20 25
// 如果自定义的数据结构要进行堆排序,那么实现operator<(const My& rhs),{}内部>是小顶堆,<是大顶堆
cout<<endl;
return 0;
}