C++ std::sort_heap
The std::sort_heap
function in C++ sorts the elements of a heap into ascending order. The function assumes the range [first, last)
is a valid heap. After the operation, the elements in the range are sorted, and the heap property is no longer maintained. This function works with random access iterators and is used in conjunction with std::make_heap
and std::pop_heap
to manage heaps.
Syntax of std::sort_heap
template <class RandomAccessIterator>
void sort_heap(RandomAccessIterator first, RandomAccessIterator last);
template <class RandomAccessIterator, class Compare>
void sort_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
Parameters of std::sort_heap
Parameter | Description |
---|---|
first, last | Random access iterators defining the range of elements to sort. The range is [first, last) . |
comp (optional) | A binary comparison function that defines the order of elements. Defaults to < . |
Return Value of std::sort_heap
This function does not return any value. It rearranges the elements in the range [first, last)
in ascending order.
Examples for std::sort_heap
Example 1: Basic Usage of std::sort_heap
This example demonstrates sorting a max-heap into ascending order:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> heap = {40, 30, 15, 10, 20};
std::make_heap(heap.begin(), heap.end());
std::cout << "Heap before sort_heap: ";
for (int n : heap) {
std::cout << n << " ";
}
std::cout << std::endl;
// Sort the heap into ascending order
std::sort_heap(heap.begin(), heap.end());
std::cout << "Sorted heap: ";
for (int n : heap) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- Include necessary headers:
<iostream>
: Used for input/output operations.<algorithm>
: Includes functions likestd::make_heap
andstd::sort_heap
for heap operations.<vector>
: Used for thestd::vector
container.
- Initialize a vector:
- A vector named
heap
is initialized with the elements{40, 30, 15, 10, 20}
. - The elements represent an unsorted collection of integers.
- A vector named
- Transform the vector into a max-heap:
- The function
std::make_heap
rearranges the elements of the vector to satisfy the max-heap property. - In a max-heap, the largest element is placed at the front of the vector (
heap[0]
).
- The function
- Display the heap before sorting:
- The program uses a for loop to print the elements of the vector in their heapified order.
- The output is:
"Heap before sort_heap: 40 30 15 10 20"
.
- Sort the heap:
- The function
std::sort_heap
sorts the elements in ascending order while maintaining the heap structure during the process. - After this operation, the heap property is no longer valid, as the elements are fully sorted in ascending order.
- The function
- Display the sorted heap:
- The program uses another
for
loop to print the elements of the vector after sorting. - The output is:
"Sorted heap: 10 15 20 30 40"
.
- The program uses another
Output:
Heap before sort_heap: 40 30 15 10 20
Sorted heap: 10 15 20 30 40
Example 2: Using a Custom Comparison Function for std::sort_heap
This example demonstrates sorting a min-heap in descending order using a custom comparison function:
#include <iostream>
#include <algorithm>
#include <vector>
bool min_heap(int a, int b) {
return a > b; // Custom comparison for a min-heap
}
int main() {
std::vector<int> heap = {10, 20, 15, 30, 40};
std::make_heap(heap.begin(), heap.end(), min_heap);
std::cout << "Min-Heap before sort_heap: ";
for (int n : heap) {
std::cout << n << " ";
}
std::cout << std::endl;
// Sort the heap in descending order
std::sort_heap(heap.begin(), heap.end(), min_heap);
std::cout << "Sorted heap in descending order: ";
for (int n : heap) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Min-Heap before sort_heap: 10 20 15 30 40
Sorted heap in descending order: 40 30 20 15 10
Exception Handling in std::sort_heap
The std::sort_heap
function does not throw exceptions on its own. However, the comparison function passed as an argument may throw exceptions, which can be caught and handled appropriately.
Example 1: Exception in Custom Comparison Function
This example demonstrates how exceptions in a custom comparison function are handled:
#include <iostream>
#include <algorithm>
#include <vector>
#include <stdexcept>
bool faulty_compare(int a, int b) {
if (a == 15 || b == 15) {
throw std::runtime_error("Comparison involving 15 is not allowed.");
}
return a < b;
}
int main() {
std::vector<int> heap = {40, 30, 15, 10, 20};
std::make_heap(heap.begin(), heap.end());
try {
// Attempt to sort the heap with a faulty comparison function
std::sort_heap(heap.begin(), heap.end(), faulty_compare);
} catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
Output:
Exception caught: Comparison involving 15 is not allowed.