How to sort Associative Arrays?

d

Solution

D's built-in associative arrays are hash tables. They're unsorted, and it makes no sense to sort them. The only time that sorting would make any sense would be when iterating over the AA, and to do that requires putting them in a new container. So, you could do something like

auto keys = aa.keys;
sort(keys);

but you can't sort the AA itself. If you want a sorted map, then you need to use something like `std.container.RedBlackTree` - though it does take a little bit of work to make it function as a map rather than a set (e.g. the sort function must sort on the key only, and when passing stuff to some functions, you need a tuple with a dummy value).

This is why Java has a `HashMap` and a `SortedMap` and why C++ has `unordered_map` (C++11) and `map`. They both are maps both they have very different characteristics - particularly with regards to sorting and lookup times.

Problem

``` float[float] aa = [2.2:7.7, 3.3:6.6, 1.1:4.4]; std.sort(aa); assert(aa == [1.1:4.4, 2.2:7.7, 3.3:6.6]); ``` The above doesn't work. How does one sort `aa` in place ?

Original source