Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

Sort associative array or SortedMap by value

Moderators: larsivi kris

Posted: 02/05/09 14:29:08 Modified: 02/05/09 14:33:28

I have a question regarding sorting of either a HashMap? or an associative array. I get some data back from a database and want to sort it. I have an id and a value and would like to sort the id's by the value. I used an associative array first with the id as key:

int[int] data;
data[id] = value;

but sorting an associative array by the value is not possible. How would this be solved in D? I looked at several solutions, but all what seems possible is to sort an array only if it is non-associative. I also had the idea to add a comparator to the SortedMap?, but didnt get it working. Is a comparator for the values in a SortedMap? possible? I also thought of a sorting iterator, but could find any information on that.

Any ideas would help.


Author Message

Posted: 02/05/09 16:28:00

Associative arrays (hashmaps like the builtin or trees like sortedmap) are by their nature already sorted by their keys to allow fast lookups, so you can't reorder them. Hash-maps probably won't be sorted in any sensible seeming way though.

So you could put the data in an array (maybe paired with keys) and sort that or put it into a SortedMap? using your data as the key.