So I have always used comparator functors in STL but never truly understood what returning a true or false meant. I had to run it and adjust the functor all the time. For instance suppose I have the following code
struct functor
{
// does returning true place a before b ?
bool operator()(int a,int b)
{
if (a < b)
return true;
return false;
}
};
int main()
{
std::priority_queue<int, std::vector<int>,functor> q;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q.push(n);
}
Could anyone please clarify this
bool operator()(int a,int b)
{
if (a < b)
return true;
return false;
}
Does returning a true place a
before b
? I am trying to come up with something like "if a is less than b than return true and true means a will be placed before b" but apparently this is not correct
Yes, if your function is
bool operator(T a, T b);
If it returns true, it means that a is placed before b in the sorted ordering. However, the priority queue is ordered so that if a is placed before b, b will be higher than a in the queue. So if
bool operator (T a, T b) { return a < b; }
is used, the "largest" element will be at the top of the queue.