Just like in a priority_queue in STL we can give our custom compare function like this:
class comp
{
bool operator()(int a, int b)
{
return a>b? 1:0;
}
};
priority_queue<int, vector<int>, comp> pq;
How can I do this for any class? I tried doing this to compare my person class object using class c
:
class person
{
public:
int height;
int age;
person(int a, int h)
{
age = a;
height = h;
}
};
template<class comparator>
class c
{
public:
vector<person>p;
void compare(person p1, person p2)
{
if(comparator comp( p1, p2))
{
p.push_back(p1);
}
}
};
class compare
{
bool operator()(person p1, person p2)
{
return p1.height> p2.height ? 1:0;
}
};
and then I created 2 person
objects and a class c
object "pq", then called the compare
function like we do in priority_queue
:
person p1(23, 85);
person p2(11, 55);
c <compare> pq;
pq.compare(p1, p2);
but it is giving this error.
error: expected primary-expression before 'comp'
if(comparator comp(p1, p2))
^~~~
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…