Priotity queue Comparison Template

Hello :)
I need to pass to a prioriy queue a pair of integers and i want the top to be according to the smallest first integer and if two are equal then according to the second one(with ascending order).
Can someone help me? Because i have no big idea of classes and messed everything up here.
Thanks
closed account (o3hC5Di1)
Hi there,

You will need to define a function object that does the comparison for you as such:

1
2
3
4
5
6
7
8
9
10
11
12
13
class compare_pq 
{
    public:
        bool operator() (int a, int b)
        {
            if (a < b) return true;
            return false;
        }
};

//use it as:

std::priority_queue<int, std::vector<int>, compare_pq()>  my_pq;


I haven't tested this, so it will probably not work out of the box - but it should give you an idea of what to do.

Hope that helps.

All the best,
NwN
that's exactly what i tried to do but without result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define pii pair < int,int >
class comp{
    public:
    bool operator()(pii a, pii b)
    {
        if(a.first>b.first)
        {
        return 0;
        }
        else if(a.first<b.first)
        {
        return 1;
        }
        else
        {
        //they are equal
            if(a.second>b.second)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
    }
}
closed account (o3hC5Di1)
Can you please be a little bit more descriptive about "not working"?
What output are you expecting and which output are you getting, for instance?

Also - I believe typedef is generally preferred for shortening data type syntax as to your #define approach.

All the best,
NwN
i use #define pii pair < int,int > every time i use pairs of integers so i know it does work ;p
Basically the code doesnt compile, so it doesnt work ;p
closed account (o3hC5Di1)
I'm not saying that won't work - I'm saying other coders will understand better what your intent is by using typedef.

Again: be more specific - if you have compiler errors, copy paste them (along with the code).
It's a lot easier for us to help you if you describe the problem clearly and concisely - that helps us help you better.

All the best,
NwN
Last edited on
It marks the first brace of main and says:


new types may not be defined in a return type


Error: extraneous 'int' ignored


Error:'main' must return int

closed account (o3hC5Di1)
... so can you please copy us your main function?

All the best,
NwN
Did you forget to put a semicolon after the class definition?
You need to post your main program also.
Thank you very very much, the problem was the semicolon ;p
Topic archived. No new replies allowed.