尝试使用该类的结构中的变量创建自定义类的优先级队列

Trying to make a priority queue of a custom class using a variable in a struct of that class(尝试使用该类的结构中的变量创建自定义类的优先级队列)
本文介绍了尝试使用该类的结构中的变量创建自定义类的优先级队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的类,目标是使 bnode 的优先级队列按顺序排列,以便具有最低计数符号的 bnode 具有最高优先级.这是我的代码:

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;

这会导致错误:错误:bnode::value"不能出现在常量表达式中

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

推荐答案

你的priority_queue是存储bnode,所以需要提供operator< 代表 bnode.

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
}

完成此操作后,无需为 priority_queue 提供第二个和第三个模板参数,默认值即可.

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;

这篇关于尝试使用该类的结构中的变量创建自定义类的优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)