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
-
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?
-
A default-constructed key should not be a valid key :)
-
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()
. -
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.