assocArray

Returns a newly allocated associative array from a range of key/value tuples or from a range of keys and a range of values.

  1. auto assocArray(Range r)
    assocArray
    (
    Range
    )
    (
    Range r
    )
    if ()
  2. auto assocArray(Keys keys, Values values)

Parameters

r Range

An input range of tuples of keys and values.

Return Value

Type: auto

A newly allocated associative array out of elements of the input range, which must be a range of tuples (Key, Value) or a range of keys and a range of values. If given two ranges of unequal lengths after the elements of the shorter are exhausted the remaining elements of the longer will not be considered. Returns a null associative array reference when given an empty range. Duplicates: Associative arrays have unique keys. If r contains duplicate keys, then the result will contain the value of the last pair for that key in r.

Examples

1 import std.range : repeat, zip;
2 import std.typecons : tuple;
3 import std.range.primitives : autodecodeStrings;
4 auto a = assocArray(zip([0, 1, 2], ["a", "b", "c"])); // aka zipMap
5 static assert(is(typeof(a) == string[int]));
6 assert(a == [0:"a", 1:"b", 2:"c"]);
7 
8 auto b = assocArray([ tuple("foo", "bar"), tuple("baz", "quux") ]);
9 static assert(is(typeof(b) == string[string]));
10 assert(b == ["foo":"bar", "baz":"quux"]);
11 
12 static if (autodecodeStrings)
13     alias achar = dchar;
14 else
15     alias achar = immutable(char);
16 auto c = assocArray("ABCD", true.repeat);
17 static assert(is(typeof(c) == bool[achar]));
18 bool[achar] expected = ['D':true, 'A':true, 'B':true, 'C':true];
19 assert(c == expected);

See Also

Meta

Suggestion Box / Bug Report