简体   繁体   中英

QMap operator <()

I'm not sure to understand the docs correctly. I want to define my own <() operator for QMultiMap in order to use a custom type and define a specific values(const Key &key) behavior.

The desired behavior is to retrieve all the values that have the same group and event of the searching key (src), and the payload string that matches the initial part of the one in src. Example:

A payload in a key in my map might be: "HUB,PRESS*". If a src matches the group and event values and has the following payload:"HUB,PRESS,3" should retrieve the above element (because the src payload begin with the same string portion).

Here my implementation:

struct event_t {
    int group;
    int event;    
    QString payload;
};

inline bool operator <(const event_t &e1, const event_t &e2)
{
    if (e1.group != e2.group) return e1.group < e2.group;
    if (e1.event != e2.event) return e1.event < e2.event;

    if (e2.payload.endsWith("*\""))
    {
        qDebug() << e1.payload << e2.payload;
        QString s2 = e2.payload.mid(0, e2.payload.size() - 2);
        QString s1 = e1.payload.mid(0, s2.size());
        s1.append("\"");
        s2.append("\"");
        return s1 < s2;
    }

    return e1.payload < e2.payload;
}

Here a simple use case:

QMultiMap<event_t, event_t> m_map;
// fill with some items, one has the key like: "HUB,PRESS*"

event_t src;
// populate it

QList<event_t> dst = m_map.values(src);

The problem is I never see a debug print of src against the available items (as I expect from the values() code ). Instead my qDebug() prints the same value for e1 e e2 (the one stored into my map) and never the src one. Ie:

"\"HUB,PRESS*\"" "\"HUB,PRESS*\""

Perhaps I didn't understand how this should work?

Here the working code:

inline bool operator <(const event_t &e1, const event_t &e2)
{
    if (e1.group != e2.group) return e1.group < e2.group;
    if (e1.event != e2.event) return e1.event < e2.event;

    if (e1.payload.endsWith("*\""))
    {
        QString s1 = e1.payload.mid(0, e1.payload.size() - 2);
        QString s2 = e2.payload.mid(0, s1.size());
        s1.append("\"");
        s2.append("\"");
        return s1 < s2;
    }

    return e1.payload < e2.payload;
}

I don't know why but the src value is contained in e1 rather than e2 as I was expecting from the values() implementation.

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