5 ms·
I agree this particular example can be confusing the first time you hit it, especially coming from other languages. It's better than the alternatives though, I
by tcwc 14y ago
I agree this particular example can be confusing the first time you hit it, especially coming from other languages.
It's better than the alternatives though, I would be interested to hear how you handle this in your version. Leaving the behaviour undefined for non-existent keys is likely to cause far worse bugs, throwing an exception would be inconsistent with the rest of the stl.
The could have left it out altogether, but would mean losing some nice properties - operator[] returning a reference makes it possible to assign into the map directly ( a[3] = 5; ). Also since the value is default initialized, you can write something like a counter easily, much like a python defaultdict:
for (auto id in ids) {
a[id] += 10;
}
You can always stick to .find and .insert if you prefer the more explicit behaviour.
- cobrausn 14y agoIn the version we ended up writing, 'operator []' is equivalent to a call to 'Get', which also returns a reference to the mapped value. In the event that key is not mapped, it asserts. If you handle the assert or have disabled runtime asserts, it returns a reference to a static value instance, so you can handle this kind of error yourself or even use the static value as a 'default' (though we never use it that way). Though not consistent with how STL works, it is consistent with how our containers work and how we use maps. YMMV. Also, since we wrote it, we're free to change the behavior if a better way manifests itself. So, if you have any suggestions, let fly.
- idupree 14y agoYou could return a proxy object that offers operator= et al, and an implicit conversion operator to T& or T const& that throws an exception if that key is not in the map. (I don't know if that would be better, since it's even more magic and it still isn't perfect.)