How do I sort associative arrays?

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 can you sort aa

?

+3


source to share


2 answers


D built-in associative hash table arrays . They are unsorted and there is no point in sorting them. The only time sorting would make any sense would be when repeating AAs, and to do this, you need to put them in a new container. So, you can do something like

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

      



but you cannot sort AA itself. If you want a sorted map, then you need to use something like std.container.RedBlackTree

- although this function requires a bit of work as a map, not a set (for example, a sort function should only sort by key, and when passing stuff to some functions, you need a tuple with dummy value).

This is why Java has HashMap

and SortedMap

and why C ++ has unordered_map

(C ++ 11) and map

. They are both maps and have very different characteristics - especially in terms of sorting and search time.

+7


source


You can't - it doesn't make sense.

Associative arrays are also known as "dictionaries" or "maps"; the particular variation in D is a hash table. These are not arrays . Sorting them can lead to quick searches.



If you need fast search times, consider this instead RedBlackTree

.

+6


source







All Articles