D - How to sort associative array ?
- Arirsi (2/2) Aug 30 2003 As title, by key or by value.
- Helmut Leitner (25/28) Aug 30 2003 You can't do this directly, because assoziative arrays are not directly
- djcurrey hotmail.com (3/31) Sep 09 2003 Can you provide an example of this? I tried by override the cmp operator
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
In article <3F5110C1.895F8E09 chello.at>, Helmut Leitner says...Arirsi wrote:Can you provide an example of this? I tried by override the cmp operator on the keys array but was unsuccessful.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
Sep 09 2003