i want to make a min priority_queue of pair integers. but what i want to do is suppose first integer of one of the pair is 10 and second is 20 and that of a another pair first is 10 and second is also 10 i want that if two having equal value of first than than the one having more value of second should be popped first.
Priority queue sorts only according to first elements. You can rather create a vector of pairs and sort function does this thing
Up vote me … I am not able to ask questions
even sort function will sort according to first element
You can perform this by using stl in c++.
EDIT : The default comparator for the priority queue is (l < r). You can see that in the constructor default parameter, By modifying the comparator in priority_queue you’d get the desired min priority queue.
bool operator() function compares the pairs. You can see that first, it will check whether the first element of pairs is equal or not if it’s equal the constructor will do as you want.(Put the pair with a larger second on top().) if not then put the pair with larger first on top().
Here’s the code
#include "bits/stdc++.h"
using namespace std;
struct compare
{
bool operator()(pair<int, int> p1,pair<int,int> p2) {
if(p1.first == p2.first)
return p1.second < p2.second;
else
return p1.first > p2.first; // ***EDIT***
}
};
int main()
{
priority_queue<pair<int,int>,vector<pair<int,int>>,compare> pq;
pq.push(make_pair(10,20));
pq.push(make_pair(2,10));
pq.push(make_pair(1,5));
pq.push(make_pair(10,10));
while(!pq.empty())
{
pair<int, int> w = pq.top();
cout << w.first << " " << w.second << endl;;
pq.pop();
}
}
guys, please upvote me. i am new here. nad not able to ask question
this will sort only according to first element …
No , sort function sorts a pairs in vector according to the two elements
#include “bits/stdc++.h”
using namespace std;
int main()
{
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
pq.push(make_pair(10,20));
pq.push(make_pair(10,10));
pq.push({10,2});
while(!pq.empty())
{
pair<int, int> w = pq.top();
cout << w.first << " " << w.second << endl;;
pq.pop();
}
}
you can declare a priority queue like this and this will do the task for you .
No…it will not work
no…its not working…it only sort according to the second element
give input
(10 20),
(10 10),
(2 10),
(1 5),
output should be
(1 5),
(2 10),
(10 20),
(10 10)
given input (10 20), (10 10), (2 10), (1 5), output should be (1 5), (2 10), (10 20), (10 10)
[1]
[1]: http://ideone.com/bUeZxs
its working …but can you please explain the logic. That will be very helpful.
yeah…I got it…Thank You
can you explain how operator works
Bolanet88.net merupakan situs agen judi bola terpercaya yang menawarkan permainan judi online terlengkap.
situs judi bola resmi
agen taruhan bola indonesia
bandar judi tangkas online uang asli
daftar akun sbobet ibcbet
Please read the edited answer.