Re: [GD-General] Eiffel
Brought to you by:
vexxed72
From: Jesse J. <jes...@mi...> - 2001-12-26 06:44:54
|
At 10:34 PM -0500 12/25/01, Thatcher Ulrich wrote: >On Sun, 23 Dec 2001, Jesse Jones wrote: > >> At 11:47 PM -0500 12/22/01, Thatcher Ulrich wrote: >> >> >An example of how the STL is not "really easy to use": >> > >> > std::hash_map<string, int> my_hash; >> > >> > ... >> > string my_key = something...; >> > int my_value = something...; >> > >> > // I want to see if my_key is in my_hash, and if so, whether >> > // its value matches my_value. >> > std::hash_map<string, int>::iterator it = my_hash.find(my_key); >> > if (it != my_hash.end() && (*it).second == my_value) >> > { >> > // Match. >> > } else { >> > // Mismatch. >> > } >> >> Try: >> if (my_hash.count(my_key) > 0) >> // match >> else >> // mismatch > >No, that's not the same test -- I want to check the value as well. I >don't think it's possible to do w/ STL without either explicity using >an iterator, or doing two lookups. Whoops, you're right of course. I wouldn't consider this a very good example of how STL is hard to use though. It's just different behavior than what you're used to. Sometimes it makes the code slightly more difficult to write, sometimes it makes it easier to write. However I do think this is one of the few places in STL that could have been designed better. As was mentioned earlier good implementations and good designs will try to catch user errors. Having operator[] add a new entry if one isn't already present might sometimes be handy, but if users make a mistake they won't know until sometime later. OTOH if operator[]'s precondition was that the key be present they'll find out right away that there's a problem. > > >I think I got that right. The iterator is just obfuscation. Whereas >> >the way you'd do it in Perl or Lua, the seemingly obvious: >> > >> > if (my_hash[my_key] == my_value) { >> > // Match. >> > } else { >> > // Mismatch. >> > } >> > >> >compiles, and leaks memory! >> >> Compiles, but shouldn't leak memory. > >It's a leak -- if my_hash[my_key] is not defined, then it allocates >memory and there's no way to safely clean it up. The above code is >bugged, end of story. It's not an STL bug though, it's a client bug. And when the hash map is destroyed the memory will be released. -- Jesse |