T[][T] -> [(k1, v1), ..., (k1, vn), ..., (kn, v1), ..., (kn, vn)]

Stanislav Blinov stanislav.blinov at gmail.com
Thu Feb 13 04:01:39 PST 2014


On Thursday, 13 February 2014 at 11:00:17 UTC, Tobias Pankrath 
wrote:
> I've got a hash map T[][T] with keys of T and values of T[]. 
> For some reason, I'll need a range of tuples (t1, t2), where t1 
> is a key and t2 is an element of the array t1 maps to. To have 
> them in order would be great, but is not necessary.
>
> I just wrote my own range type and it works. But I wonder how 
> would I do it with phobos utilities?

A byPair range has been proposed long ago:

https://d.puremagic.com/issues/show_bug.cgi?id=5466

> I came up with this:
>
> int[][int] hash = [1 :[1,2,3,4], 2:[3,1,2,3], 4:[2,3,1,3]];
> auto x = hash.keys.map!(x => tuple(x, hash[x]))
>                   .map!(x => zip(repeat(x[0]), x[1]));
>
> Is there any other way to create a range of simple (key,value) 
> pairs for the array, but needs to allocate (hash.keys return an 
> array of keys) and then again look up every key.

import std.algorithm : zip;
import std.traits    : isAssociativeArray;

auto byKeyValuePair(AA)(AA aa) if (isAssociativeArray!AA)
{
	return zip(aa.byKey, aa.byValue);
}


More information about the Digitalmars-d-learn mailing list