Home > Enterprise >  Initialize priority_queue without constructor
Initialize priority_queue without constructor

Time:02-25

I have a priority_queue with custom comparator:

using A = ...

class A {
public:
    A() {
        auto cmp = [](DataPair left, DataPair right) {
            return left.second > right.second;
        };
        std::priority_queue<DataPair, std::vector<DataPair>, decltype(cmp)> q(cmp);
        q_ = q;
    }

private:
    std::priority_queue<DataPair, std::vector<DataPair>, decltype(cmp)> q_;
};

Is there a way to initialize priority_queue without constructor ?

CodePudding user response:

You cannot use decltype(cmp) for the member type when cmp is local to the constructor. You can move the definition of the comparator out of the constructor and use the default constructor of priority_queue which default constructs the comparator:

struct cmp {
    bool operator()(const DataPair& left,const DataPair& right) {
        return left.second > right.second;
    }
};

class A {
public:

private:
    std::priority_queue<DataPair, std::vector<DataPair>, cmp> q_;
};
  •  Tags:  
  • c
  • Related