Search code examples
associative-arrayd

Removing any element from an associative array


I'd like to remove an(y) element from an associative array and process it. Currently I'm using a RedBlackTree together with .removeAny(), but I don't need the data to be in any order. I could use .byKey() on the AA, but that always produces an array with all keys. I only need one at a time and will probably change the AA while processing every other element. Is there any other smart way to get exactly one key without (internally) traversing the whole data structure?


Solution

  • There is a workaround, which works as well as using .byKeys():

    auto anyKey(K, V)(inout ref V[K] aa)
    {
        foreach (K k, ref inout(V) v; aa)
            return k;
        assert(0, "Associative array hasn't any keys.");
    }
    

    For my needs, .byKeys().front seems to be fast enough though. Not sure if the workaround is actually faster.