algorithm - STL C++

push_heap()

Declaration

template <class RandomAccessIterator>
void push_heap(
	RandomAccessIterator xFirst,
	RandomAccessIterator xLast
);

Description

This function pushes the element pointed to by "xLast" into the heap defined by the elements in the range "xFirst" up through the one before "xLast." The result is a heap that is one element longer than it was. The overloaded version uses the function "xComp" as a less than comparison function.

Header Include

#include <algorithm>

Overloads

template <class RandomAccessIterator, class BinaryPred>
void push_heap(
	RandomAccessIterator xFirst,
	RandomAccessIterator xLast,
	BinaryPred xComp
);

Example

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
	using namespace std;

	// Create a vector instance
	vector<int> qV;
	qV.push_back(45);
	qV.push_back(83);
	qV.push_back(3);
	qV.push_back(49);
	qV.push_back(97);
	qV.push_back(16);
	qV.push_back(34);
	// Make the vector a heap
	make_heap(qV.begin(), qV.end());
	// Add an extra element to the end of the heap
	qV.push_back(51);

	vector<int>::iterator qIter;
	// Output the heap and last element
	cout << "Output heap with last : ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;

	// push the last int (51) into the heap
	push_heap(qV.begin(), qV.end());

	// Output the new vector
	cout << "Output the entire heap: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;

	// Keep the window open
	cin.get();
	return 0;
}

Output

push_heap() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.