Reputation: 23
I'm looking at a declaration of a priority queue in C++ but I don't quite understand it.
priority_queue<string, vector<string>,function<bool(string,string)>>
min_heap([] (const string& a,const string& b) {return a.size()>=b.size();});
What is the purpose of the brackets []? Is that part of the function definition?
Also, would I be able to implement the same thing by using a bool operator?
Upvotes: 1
Views: 182
Reputation: 119641
The entire expression
[] (const string& a,const string& b) {return a.size()>=b.size();}
is a lambda expression. It is an object of an unnamed class that can be called with two string arguments, a
and b
, and returns bool
.
You could also write such a class yourself (in that case, it would have a name):
struct Comp {
bool operator()(const string& a, const string& b) {
return a.size() > b.size();
}
};
priority_queue<string, vector<string>, Comp> min_heap;
// a value of type Comp will be value-initialized
Note that the comparator must be a strict weak ordering, so you must use >
instead of >=
.
If performance matters, it is better to define a named class, because the function call operator can be inlined.
Upvotes: 1