efficient and safe way to iterate on associative array?

aki via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 4 19:37:35 PST 2016


On Friday, 4 March 2016 at 16:46:35 UTC, Steven Schveighoffer 
wrote:
>
> You cannot add or remove keys. You can modify values for 
> existing keys.
>
> Note, in your code, this would not cause a problem, since 
> setting hash to null just removes the reference from the local 
> variable 'hash', it does not alter the AA in any way.
>
> In dcollections, all containers support "purging", or iterating 
> through elements, removing the current element if desired 
> before moving to the next. But I haven't touched this library 
> in ages, I don't know if it still compiles even.
>
> -Steve

Thank you for it. Now I know.
I will copy and modify AA source to customize. (src/rt/aaA.d)
I wonder what if D support safe variant like safeByKeyValue.
Actually it seems easy (in aaA.d):

     bool _aaRangeEmpty(Range r)
     {
         return r.impl is null || r.idx == r.dim;
     }

can be changed to:
     bool _aaRangeEmptySafe(Range r)
     {
         if(r.impl is null || r.idx >= r.dim) return true;
         if (!r.buckets[r.idx].filled) throw xxxException();
         return false;
     }
It can become safe by a cost of small overhead.

-- Aki.



More information about the Digitalmars-d-learn mailing list