I wish that container.contains() would return the actual value...
-
Hey...
Am I the only one who finds doing this :
if(map.cotnains(key)){ auto *item = map[key]; map.remove(key); delete item; }
Could have been handled by
if(auto *item = map.contains(key)){ map.remove(key); delete item; }
And so on and so forth?
1 Less function call but on a large scale, it might help? -
@dariusz It would be counter-intuitive, because "contains" does what it means: it tells you whether container contains something. A simple yes/no answer. Also, what should it return if there is no such element?
Last but not least there is https://doc.qt.io/qt-5/qvector.html#value or https://doc.qt.io/qt-5/qmap.html#value which does what you want... -
@jsulm said in I wish that container.contains() would return the actual value...:
@dariusz It would be counter-intuitive, because "contains" does what it means: it tells you whether container contains something. A simple yes/no answer. Also, what should it return if there is no such element?
I was thinking of it lately, I suppose containsPtr(), would return either nullptr=false or item = true ?
Last but not least there is https://doc.qt.io/qt-5/qvector.html#value or https://doc.qt.io/qt-5/qmap.html#value which does what you want...
Heee I never thought of using value()! So if its map of Ptrs, would default value return be a nullptr? As if he just make new item from default constructor then thats no help, I will have to test if the item is "valid" and then delete if its not mhmmm
-
Hi,
The function takes two parameters. You can pass the default value you want to get if the key is not found in the map.
-
@dariusz said in I wish that container.contains() would return the actual value...:
if(map.cotnains(key)){ auto *item = map[key]; map.remove(key); delete item; }
This whole block can be replaced by 1 line:
delete map.take(key);
take()
returns the item and removes it from the map. If the map does not contain key,take()
returns a default value (nullptr, in your case). It is safe to delete nullptr as long as you don't use a non-standard deallocator. -
Any better way of solving this double search ?
Yes, the classic stl style:
auto it = map.find(key); if (it != map.end()) { *it = "do Stuff"; } else { qDebug() << "invalid key ? "; }
If you don't like that it's one line longer you can use c++17:
if (auto it = map.find(key); it != map.end()) {
-
@dariusz said
me not knowing 60% of STL
I would concentrate on fixing that. You're missing a large chunk of ready to use stuff and you'll be reinventing a lot of wheels without it.