associative arrays: iteration is finally here

Bill Baxter wbaxter at gmail.com
Thu Oct 29 10:14:32 PDT 2009


On Thu, Oct 29, 2009 at 9:57 AM, KennyTM~ <kennytm at gmail.com> wrote:
> On Oct 29, 09 23:59, Bill Baxter wrote:
>>
>> On Thu, Oct 29, 2009 at 8:39 AM, Andrei Alexandrescu
>> <SeeWebsiteForEmail at erdani.org>  wrote:
>>>
>>> Leandro Lucarella wrote:
>>>>
>>>> Andrei Alexandrescu, el 28 de octubre a las 20:29 me escribiste:
>>>>>>>
>>>>>>> Your test looks something up and then removes it.
>>>>>>>
>>>>>>>
>>>>>>> Andrei
>>>>>>
>>>>>> Well, my extended test case looks something up, manipulates the
>>>>>> found value, and then possibly removes it.
>>>>>
>>>>> Ok, I understand your points, thanks for explaining.
>>>>
>>>> What about and overload of remove() like this:
>>>> bool remove(in T key, out U value);
>>>>
>>>> If the element was present, it's returned in "value", so you can
>>>> manipulate it. I thought about just returning a pointer:
>>>> U* remove(in T key);
>>>>
>>>> But I guess that pointer would point to the element stored in the the AA
>>>> private data, but that element was just removed, so bad things would
>>>> happen, that's why the only option is to copy the data, right?
>>>
>>> I think this all is overdoing it. First, I disagree that remove should
>>> ever
>>> throw an exception. It's not a code that the user is supposed to check
>>> (with
>>> dire consequences if she doesn't), it's just additional information just
>>> in
>>> case you need it.
>>>
>>> I think bool remove(key) is better than all other designs suggested so
>>> far.
>>
>> I agree with the folks who say it's error-prone.  I can just see
>> myself now removing a key I know is in the dictionary and being
>> baffled when my program fails somewhere later on because I typed
>> aa.remove("theKey") when it should have been aa.remove("thekey").  I
>> knew it was there so I didn't want to clutter up my code with a check
>> for it.
>
> Um what? aa["theKey"] = 1 doesn't fail, why should aa.remove("theKey") be
> special?

Huh?  aa["theKey"] also doesn't delete entries, so why should it have
any bearing on what remove does?  The closest analogy would be the
case where aa["theKey"]=1 can't do what you ask it to, which would be
an out-of-memory error, which does generate an error of some kind, I
think.

> (Meanwhile, C++'s map::erase returns the number of elements removed,

Erase is also used for multimaps, so it's not exactly apples to
apples.  Your other examples are ok AFAIK.

>
> void discard(K,V)(ref V[K] aa, in K key) {
>  if (!aa.remove(key)) assert(false);
> }
>
> ...
>
> aa.discard("theKey");

Yep, that would be perfect if it were part of the standard AA
interface.  That would actually be my preferred solution, to have two
methods for removing elements from AAs.  One that throws and one that
doesn't.

--bb



More information about the Digitalmars-d mailing list