Best ways to declare associative arrays
Nicholas Wilson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Mar 12 00:16:41 PST 2017
On Sunday, 12 March 2017 at 07:58:40 UTC, helxi wrote:
> How would an experienced programmer declare an associative
> array of strings that has 2 keys?
>
> My initial impression was string[string][2] my_array; which
> does not seem to work.
>
> Here is a snippet of the code I am working on:
>
>
> import std.string;
> import std.stdio;
>
>
> string[string] change(ref string[string] arg_array){
> //..
> arg_array["first"] = strip(readln());
> //..
> arg_array["second"] = strip(readln());
> //..
> return def;
> }
>
You appear to be confused about the way arrays work.
string[string] foo; //declares an assoc array of strings, index
by string
string[string][2] bar; // declares a static array of two
string[string]
foo = { "key1" : "some data", "key2" : "some other data" }; //
initialise foo with some data
foo["blarg"] = "fxgsdzfcxf"; // insert some more data
> associative array of strings that has 2 keys?
is a regular associative array that has two entries. much like
the difference between
int[] baz = [1 ,2]; // has two elements
int[][2] quux; // a static array of length 2 whose elements are
of type int[]
> void main(){
> string[string][2] test; // remove the `[2]`
> change(string[string] test);
just do
change(test);
it is invalid syntax to have a type before the variable in a
function call, unless you were trying to cast it, in which use
`cast(type)(expression)`
> }
>
If you wish to reserve capacity for the array, use
`arr.reserve(N)` to allocate memory enough to hold N elements.
More information about the Digitalmars-d-learn
mailing list