Bug 382702

Summary: Comparison between QMap keys false positive
Product: [Developer tools] clazy Reporter: nicolas.kniebihler
Component: generalAssignee: Unassigned bugs mailing-list <unassigned-bugs>
Status: RESOLVED NOT A BUG    
Severity: normal CC: smartins
Priority: NOR    
Version: unspecified   
Target Milestone: ---   
Platform: MacPorts   
OS: macOS   
Latest Commit: Version Fixed In:
Sentry Crash Report:

Description nicolas.kniebihler 2017-07-25 10:13:02 UTC
Hi,

I use clazy v1.2.

This code is detected as a container-anti-pattern :

    QMap<int, int> map1;
    QMap<int, int> map2;
    bool res = map1.keys() == map2.keys();

but I don't see another way to do a comparison bewteen keys.
Comment 1 Sergio Martins 2017-07-25 10:28:44 UTC
This is not a false positive, check https://code.woboq.org/qt5/qtbase/src/corelib/tools/qhash.h.html#_ZNK5QHash4keysEv to see how keys() is implemented, it allocates and fills a new container


There's no easy way, but you could do:

bool keysEqual(const QMap<int, QString> &map1, const QMap<int, QString> &map2)
{
    if (map1.size() != map2.size())
        return false;

    for (auto it1 = map1.keyBegin(), it2 = map2.keyBegin(), e1 = map2.keyEnd(); it1 != e1; ++it1, ++it2) {
        if (*it1 != *it2)
            return false;
    }

    return true;
}


Which is a couple orders of magnitude faster
Comment 2 nicolas.kniebihler 2017-07-25 11:41:25 UTC
Thanks! :)
As there is no built-in way to compare the keys of 2 QMaps, it would be interesting, maybe, to mention your answer in the README of container-anti-pattern.
And it would also be interesting to tell Qt developers about this issue, so that they can maybe add a QMap::compareKeys method ^^ I will look into that...
Comment 3 nicolas.kniebihler 2017-07-25 11:57:10 UTC
If you're interested: https://bugreports.qt.io/browse/QTBUG-62142