Simplest way to create an array from an associative array which its contains keys and values?

Andrej Mitrovic andrej.mitrovich at gmail.com
Tue Jan 7 14:09:35 PST 2014


On 1/7/14, Craig Dillabaugh <cdillaba at cg.scs.carleton.ca> wrote:
> In other words while:
>
>      auto range = aa.byKey.map!(a => chain(a.only, aa[a].only));
>      string[] array = range.join;
>
> Saves a few lines of code, and looks cooler, it seems that the
> trivial foreach loop version is very easy:
>
> string[] array;
>
> foreach (key, value; aa) {
> 	array ~= key;
> 	array ~= value;
> }

OP asked for an array, however the reason I showed the example is
because you can get a range that way, which is lazy and will not
allocate:

auto items = aa.byKey.map!(a => chain(a.only, aa[a].only)).joiner;  //
no allocations at all
writeln(items);

So there's a huge difference, as you're saving memory (and CPU time if
you don't want to walk through the entire list).


More information about the Digitalmars-d-learn mailing list