foreach for string[string]AA

ikod via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 28 07:33:46 PST 2017


On Tuesday, 28 February 2017 at 15:15:00 UTC, Anton Pastukhov 
wrote:
> I can't see the logic in AA foreach order. Consider this code:
>
> ```
> void main() {
>     string[string] test = [
>         "one": "1",
>         "two": "2",
>         "three": "3",
>         "four": "4"
>     ];
>
>     import std.stdio:writeln;
>
>     foreach(k, v; test) {
>         writeln(k);
>     }
> }
>
> Output:
> three
> two
> one
> four
>
> I was sure output should be
> one
> two
> three
> four

AA implemented as hash table, so it doesn't preserve insertion 
order. You have to sort keys when you need:

import std.algorithm;
import std.stdio;
void main() {
	auto aa = ["one":1,
			   "two":2
			   ];
	foreach(k; sort(aa.keys)) {
		writeln(k);
	}
}


More information about the Digitalmars-d-learn mailing list