'C++ how to declare an array of priority_queue with customed comparator
With the idea from: declaring a priority_queue in c++ with a custom comparator ,
I tried to use lambda as comparator for the priority_queue, but when I tried to declare an array of it, error comes.
codes:
`
class Klass{public:int raw_hash;int name;};
bool PriorByRaw(Klass a, Klass b){return a.raw_hash > b.raw_hash;}
auto prior = [](Klass a, Klass b){return PriorByRaw(a, b);};
//here comes the error before "[10]": expected a ';'
priority_queue<Klass, vector<Klass>, decltype(prior)> pq(prior)[10];
`
The question is how can I declared an array of priority_queue in this manner? Or is there any other solution? As one day I may need a priority que which use other functions as comparator (say "PriorByName"), overriding the less function for the "Klass" looks not good.
I've tried but didn't work:
priority_queue<Klass, vector<Klass>, decltype(prior)> pq(prior)[10];
priority_queue<Klass, vector<Klass>, decltype(prior)> (pq(prior))[10];
Solution 1:[1]
You can do the following to achieve what you want:
bool PriorByRaw(Klass const & a, Klass const & b) { return a.raw_hash > b.raw_hash; }
class KlassCompare
{
public:
bool operator() (Klass const & a, Klass const & b) const
{
return PriorByRaw(a, b);
}
};
priority_queue<Klass, vector<Klass>, KlassCompare> pq[10];
Several comments:
I replaced passing the
Klass
objects byconst&
instead of by value, since this is more efficient. Is there any reason you passed it by value ?The main issue is to replace the lambda with a comparator class with
operator()
. Using the lambda anddecltype(prior)
requires the compiler to construct a new instance of a lambda which is not allowed. MSVC gives the following error for using the lambda:"error C3497: you cannot construct an instance of a lambda"
You can look
C3497
up if you'd like to get more info.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |