Search code examples
c++qtqmap

How I can define a QMap with struct as key


I try to define a QMap which it's key is a C++ structure.

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

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

But when I compile this code, I get the following compile error:

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

Solution

  • The order of the elements in the map is determined by calling operator< of the keys. From documentation:

    [...] The key type of a QMap must provide operator<() specifying a total order. Since Qt 5.8.1 it is also safe to use a pointer type as key, even if the underlying operator<() does not provide a total order.

    One way to implement it is for example:

    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);
        }
    };