foreach for string[string]AA

Anton Pastukhov via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 28 08:25:16 PST 2017


On Tuesday, 28 February 2017 at 15:44:46 UTC, bachmeier wrote:
> On Tuesday, 28 February 2017 at 15:33:46 UTC, ikod wrote:
>
>> 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);
>> 	}
>> }
>
> That will only work if sorting recovers the insertion order. An 
> easy way to save the insertion order would be to use an array 
> of structs. If an associate array is really needed, you can 
> create a struct that contains the associative array and a 
> string[] holding the keys.

Thank you for quick replies. I'm used to arrays in PHP that are 
actually ordered maps, so I was expected the same from D's AAs. 
For now I'm fine with array of structs.


More information about the Digitalmars-d-learn mailing list