【问题标题】:How I can define a QMap with struct as key我如何定义一个以结构为键的 QMap
【发布时间】:2021-05-02 21:15:00
【问题描述】:

我尝试定义一个 QMap,它的关键是 C++ 结构。

struct ProcInfo_S
{
    quint8 tech = 0;
    quint8 direction = 0;
    quint8 category = 0;
};

QMap<ProcInfo_S, uint64_t> G;
G[{2,3,4}] = 2;

但是当我编译这段代码时,我得到以下编译错误:

error: no match for ‘operator<’ (operand types are ‘const MainWindow::MainWindow(QWidget*)::ProcInfo_S’

【问题讨论】:

    标签: c++ qt qmap


    【解决方案1】:

    map中元素的顺序是通过调用键的operator&lt;来确定的。来自documentation

    [...] QMap 的键类型必须提供 operator

    一种实现方式例如:

    struct ProcInfo_S
    {
        quint8 tech = 0;
        quint8 direction = 0;
        quint8 category = 0;
        bool operator<( const ProcInfo_S& other) const {
             return std::tie(tech,direction,category) < std::tie(other.tech,other.direction,other.category);
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多