www.digitalmars.com         C & C++   DMDScript  

D - How to sort associative array ?

reply Arirsi <Arirsi_member pathlink.com> writes:
As title, by key or by value.
thanks.
Aug 30 2003
parent reply Helmut Leitner <helmut.leitner chello.at> writes:
Arirsi wrote:
 
 As title, by key or by value.
 thanks.

You can't do this directly, because assoziative arrays are not directly sortable because of their implementation (has nothing to do with D). But it is not difficult to create a sorted list, e. g. sorted by the keys: alias char [] String; int main () { int [String] age; age["Peter"]=17; age["Adam"]=6; age["Laura"]=8; age["Nora"]=6; String [] keys=age.keys.sort; String name; for(int i=0; i<keys.length; i++) { name=keys[i]; printf("%.*s: %d\n",name,age[name]); } return 0; } You could do it in a similar way for values (age.values), but depending on the situation you might need to create a new map to find back to the corresponding keys. -- Helmut Leitner leitner hls.via.at Graz, Austria www.hls-software.com
Aug 30 2003
parent djcurrey hotmail.com writes:
In article <3F5110C1.895F8E09 chello.at>, Helmut Leitner says...
Arirsi wrote:
 
 As title, by key or by value.
 thanks.

You can't do this directly, because assoziative arrays are not directly sortable because of their implementation (has nothing to do with D). But it is not difficult to create a sorted list, e. g. sorted by the keys: alias char [] String; int main () { int [String] age; age["Peter"]=17; age["Adam"]=6; age["Laura"]=8; age["Nora"]=6; String [] keys=age.keys.sort; String name; for(int i=0; i<keys.length; i++) { name=keys[i]; printf("%.*s: %d\n",name,age[name]); } return 0; } You could do it in a similar way for values (age.values), but depending on the situation you might need to create a new map to find back to the corresponding keys. -- Helmut Leitner leitner hls.via.at Graz, Austria www.hls-software.com

Can you provide an example of this? I tried by override the cmp operator on the keys array but was unsuccessful.
Sep 09 2003