Thread overview
How to sort associative array ?
Aug 30, 2003
Arirsi
Aug 30, 2003
Helmut Leitner
Sep 09, 2003
djcurrey
August 30, 2003
As title, by key or by value.
thanks.


August 30, 2003

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
September 09, 2003
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.