Re: [GD-General] Eiffel
Brought to you by:
vexxed72
|
From: Thatcher U. <tu...@tu...> - 2001-12-26 03:34:20
|
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.
> >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.
-Thatcher
|