O(1) "popAny" for associative array?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Dec 11 10:33:26 PST 2014


On 12/11/2014 10:27 AM, Andrew Klaassen wrote:

 > If it is correct, is there any way to do it in D?
 >
 > Do I assume correctly that "myarray.keys[0]" would not meet the O(1)
 > requirement?

Correct. keys() is eager. For O(1) you want byKey(), which returns a 
lazy range but the code is less than pretty:

import std.stdio;

void main()
{
     auto aa = [ 1 : "one", 2 : "two" ];

     while (true) {
         auto keys = aa.byKey;

         if (keys.empty) {
             break;
         }

         aa.remove(keys.front);
     }
}

Ali



More information about the Digitalmars-d-learn mailing list