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:
Output:
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();
}
}
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...
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 largest number of dependents should be removed first.
Help C++ Write a string class. To avoid conflicts with other similarly named classes, we will call our version MyString. This object is designed to make working with sequences of characters a little more convenient and less error-prone than handling raw c-strings, (although it will be implemented as a c-string behind the scenes). The MyString class will handle constructing strings, reading/printing, and accessing characters. In addition, the MyString object will have the ability to make a full deep-copy of itself...