Question

In C++ if needed,

(Weight: 2096) Programming: Write a Compare function class that inserts Person objects in a priority queue based on the numbe

0 0
Add a comment Improve this question Transcribed image text
Answer #1

This is the compare function that you need. For any clarifications, please comment and in case the answer helps please upvote.

struct CompareDependencies {
bool operator()(Person const& p1, Person const& p2)
{
// return true when p1 has lower dependencies than p2
return p1.dependencies < p2.dependencies;
}
};

I have also attached a sample code for testing the functionality:

#include <iostream> #include queue > using namespace std 1 4 class Person //Person class that stores the name and the count o16 int main() 18 priority queue<Person, vector<Person>, CompareDependencies>pg: Person pl,p2,p3,p4,p5,p6: //create 6 people p

Output:

Ronaldo 30 Suarez 23 Messi 23 Torres 14 Alba 12 Benzema 10 Process returned e (8x0) execution time : 0.212 s Press any key to

Typed code:

#include <iostream>
#include <queue>
using namespace std;
class Person{ //Person class that stores the name and the count of dependencies
public:
int dependencies;
string name;
};
struct CompareDependencies {
bool operator()(Person const& p1, Person const& p2)
{
// return true when p1 has lower dependencies than p2
return p1.dependencies < p2.dependencies;
}
};
int main()
{
priority_queue<Person, vector<Person>, CompareDependencies> pq;
Person p1,p2,p3,p4,p5,p6; // create 6 people
p1.dependencies = 10; p1.name = "Benzema";
p2.dependencies = 12; p2.name = "Alba";
p3.dependencies = 14; p3.name = "Torres";
p4.dependencies = 23; p4.name = "Messi";
p5.dependencies = 30; p5.name = "Ronaldo";
p6.dependencies = 23; p6.name = "Suarez";

// Insert them in the priority queue
pq.push(p1);
pq.push(p2);
pq.push(p3);
pq.push(p4);
pq.push(p5);
pq.push(p6);

// Print their data
while(!pq.empty()){
Person temp = pq.top(); // extract the top element of the priority queue
cout << temp.name << " " << temp.dependencies<<endl;
pq.pop();
}
}

Add a comment
Know the answer?
Add Answer to:
In C++ if needed, (Weight: 2096) Programming: Write a Compare function class that inserts Person objects in a priority queue based on the number of dependents a person has. The Person object with the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT