priority queue using stl in c++

guys i am trying to implement priority queue in c++ using stl .
my code is given below :

#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
class compa
{
    public:
    bool compar(const int&a,const int& b)const
    {
       return(a<b);
    }
};
int main()
{
    int i,k;
    priority_queue<int,vector<int>,compa> q;
    for(i=0;i<4;i++)
    {
        cin>>k;
        q.push(k);
    }
    while(!q.empty())
    {
        k=q.top();
        cout<<k<<" ";
        q.pop();
    }
    return 0;
}

i want to implement priority queue to give elements priority in reverse order i.e highest priority to smallest and so on…
please tell me where i am going wrong

Correct way how to do this is:

#include<cstdio>
#include<iostream>
#include<queue>

using namespace std;

class compa {
	public:
	bool operator() (const int& a,const int& b) const {
	   return a < b;
	}
};

int main() {
	int i,k;
	compa c;
	priority_queue<int, vector<int>, compa> q(c);
	for(i=0;i<4;i++)
	{
		cin>>k;
		q.push(k);
	}
	while(!q.empty())
	{
		k=q.top();
		cout<<k<<" ";
		q.pop();
	}
	return 0;
}

But I’m not so good in c++ to tell you, why this does NOT work

priority_queue<int, vector<int>, compa> q(compa());

I also understand that you want to try this, otherwise you do not need to write your own compare function for standard types.

So this code works as you wanted - greater first

int main() {
	int i,k;
	priority_queue<int> q;
	for(i=0;i<4;i++)
	{
		cin>>k;
		q.push(k);
	}
	while(!q.empty())
	{
		k=q.top();
		cout<<k<<" ";
		q.pop();
	}
	return 0;
}

and to do reverse simply change the type to

priority_queue<int, vector<int>, greater<int> > q;
4 Likes

thanks…

Don’t forget to include #include when using greater

in my environment I didn’t need this…

//