Trying to make a priority queue of a custom class using a variable in a struct of that class

梦想的初衷 提交于 2019-12-02 10:33:21

问题


So here are my classes, the goal is to make a priority queue of bnode that go in order, so that the bnode with the symbol with the lowest count has the highest priority. Here's my code:

struct symbol {
    explicit symbol(char av = 0, int ac = 0) : value(av), count(ac) { }
    char value; // actual symbol, by default 0 (empty)
    int count;  // count of the symbol, by default 0
}; // symbol

// compare two symbols
// symbol with a lower count is "less than" symbol with a higher count
inline bool operator<(const symbol& lhs, const symbol& rhs) {
    return ((lhs.count < rhs.count) || (!(rhs.count < lhs.count) && (lhs.value < rhs.value)));
} // operator<

template <typename T> struct bnode {
    explicit bnode(const T& t = T(), bnode* l = 0, bnode* r = 0)
        : value(t), left(l), right(r) { }

    T value;      // payload

    bnode* left;  // left child
    bnode* right; // right child
}; // struct bnode

#endif // SYMBOL_HPP

//and here is me trying to make a priority queue:

std::priority_queue<bnode<symbol>,std::vector<bnode<symbol> >, std::less<std::vector<bnode<symbol> >::value_type::value> > queue;

this results in the error: error: ‘bnode::value’ cannot appear in a constant-expression


回答1:


I reckon you want this:

 std::priority_queue<bnode<symbol>, std::vector<bnode<symbol> >, 
      std::less<std::vector<bnode<symbol> >::value_type> > queue;



回答2:


Your priority_queue is storing bnode<symbol>, so you need to provide operator< for bnode.

template <typename T>
bool operator<(bnode<T> const& l, bnode<T> const& r)
{
    // perform comparison
}

Once you've done that, there's no need to provide the second and third template arguments for priority_queue, the defaults work.

std::priority_queue<bnode<symbol> > queue;

Or if you want to specify all the template arguments

std::priority_queue<bnode<symbol>, 
                    std::vector<bnode<symbol> >, 
                    std::less<bnode<symbol> > > queue;


来源:https://stackoverflow.com/questions/29784351/trying-to-make-a-priority-queue-of-a-custom-class-using-a-variable-in-a-struct-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!