我如何定义一个以结构为键的 QMap

问题描述

我尝试定义一个 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’

解决方法

映射中元素的顺序是通过调用键的 operator< 来确定的。来自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);
    }
};