简体   繁体   中英

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];

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:

  1. I replaced passing the Klass objects by const& instead of by value, since this is more efficient. Is there any reason you passed it by value?

  2. The main issue is to replace the lambda with a comparator class with operator() . Using the lambda and decltype(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM