Can I make QMaps error when you [] on a key not in the map?
-
If you index a key not in the QMap, Qt automatically creates a new T for you and returns it. This is awful and prone to causing problems because on the surface it looks like everything is fine (no exceptions), but you are getting invalid data which can cause cryptic problems down the line. It also forces you to define a default constructor which may not even be appropriate.
Right now I've just been making default constructors assert to fix this problem, but sometimes I will use maps for data types that aren't under my direct control. Is there any way for me to force a QMap to throw exceptions when indexing keys not in the map like I get when I go out of range on an iterator/vector, or some alternative data structure that is not flawed like this?
-
Hi,
It's not a flaw. You can see that the std::map [] operator does the same thing.
If you really need something to throw an error, then you can change to std::map and its
at
method -
I'd suggest using the non-const version of find() to determine if a key is present or for modifying elements that you know exist.
{ mymap::iterator i; if (i=map.find(key)) != map.end()) { // do something with i } else { // conditionally do map[key]=value // if insertion is your intention } }
-
2 solutions:
If you want to control the default value returned without the missing key being added to the map you can useQMap::value
. If you want to error-handle then adopt @Kent-Dorfman 's answer usingfind()
/constFind()
to know if an entity exists and operate on it