简体   繁体   中英

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’

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM