Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Looking for an alternative approach to avoid "clazy-container-anti-pattern" in an if-clause



  • I get a warning allocating an unneeded temporary container from a code snippet like this:

    		if (QMultiMap<T,U>().keys(someVariableOfTypeU).isEmpty()) {
    			[...]
    		}
    

    I wonder how I can change the if clause to avoid that unnecessary allocation.

    I hope I elaborated enough by providing that pseudo-codish example above.

    Thanks in advance


  • Lifetime Qt Champion

    use Q(Multi)Map::key()



  • Thanks for the reply. However, the documentation for const Key QMap::key(const T &value, const Key &defaultKey = Key()) const states:

    Returns the first key with value value, or defaultKey if the map contains no item with value value. If no defaultKey is provided the function returns a default-constructed key.

    How am I supposed to distinguish between not found and default key when a default-constructed key might be a valid key in the map?


  • Lifetime Qt Champion

    A default-constructed key should not be a valid key :)



  • Given that constraint, okay. Can you point to any source that explains, why exactly a default-constructed key should not be a valid key, or why this is considered bad style?



  • There is no optimisation behind QMap::key so you can just do it manually:

    auto keyIter = map.constBegin(), iEnd = map.constEnd();
    for(;keyIter !=iEnd && keyIter.value() != someVariableOfTypeU;++keyIter){}
    if(keyIter ==iEnd){
    ///[...]
    }
    

  • Lifetime Qt Champion

    Hi,

    Wouldn't QMap::find get you what you want ?



  • Thanks,
    QMultiMap::find() searches by key and value, I need to know whether one specific value is somewhere in the map, no matter which key(s) it is associated with.

    according to @VRonin's suggestion, I simply iterate through the whole map manually now, just incrementing a counter on ocurrence. This avoids creating an extra container for the task and should not be any slower than QMultiMap::keys().


  • Lifetime Qt Champion

    My bad, I misunderstood your search pattern.

    From a reading point of view, I would have gone with std::find_if unless you want all the possible key that contains the value.


Log in to reply