C++ std::push_heap with std::vector














































C++ std::push_heap with std::vector



 This article is about the push_heap() algorithm function with std::vector container. It is
 an STL algorithm in <algorithm> header file. It places a new element in the last-1 position 
 when a heap of ranhe [first, last-1) is given. After a heap is created then the push_heap 
 preserves the characteristics of the heap.
 
push_heap() can take two forms:
(1) template <class RandomAccessIterator> void push_heap (RandomAccessIterator first, RandomAccessIterator last); (2) template <class RandomAccessIterator, class Compare> void push_heap (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
In 1st is the default case and the 2nd one is the custom case. It uses comp function for
 the comparison. comp is a binary function which accepts 2 values and returns a bool value
 which indicates whether the first element is less than the second or not. If the heap is not
 empty or one element heap then this comp function is used.

Here the first definition is discussed.

 Program:
 Marks of few students are stored in a database. Enter new marks of some students and
 dispaly the highest marks.

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

using namespace std;

int main()
{
int i, n, m;
// marks of the students
vector<int> marks{98,86,45,78,63,85,56,69};

make_heap(marks.begin(), marks.end());

cout<<"Enter the number of students whose new marks is to be entered: ";
cin>>n;

cout<<"Enter the marks: ";
for(i=0;i<n;i++)
{
cin>>m;
marks.push_back(m);
push_heap(marks.begin(), marks.end());
}

cout<<"Highest Marks: "<<marks.front()<<endl;
return 0;
}

Comments