sort associative array on values

Daniel Keep daniel.keep.lists at gmail.com
Thu May 10 06:55:53 PDT 2007



Jan Hanselaer wrote:
> Hi,
> 
> It is easy to output a associative array sorted on his keys but does anyone 
> know how to do it with the values sorted?
> 
> I use associative arrays for frequency tables (for char[] en char) and I 
> would like to output those sorted by value, and if that would be possible, 
> also by key for equal values. Anyone ever tried this of has any ideas?
> 
> Thanks in advance!
> Jan 

I would imagine you would need a reverse mapping from value->key, sort
that, and go from there.  You could probably do it with an array of structs:

struct ValueKey!(vT, kT)
{
    vT value;
    kT key;

    int opCmp(ValueKey!(vT,kT) rhs)
    {
        return (value < rhs.value)
            : -1
            ? ((key < rhs.key)
                : -1
                ? 1);
    }
}

ValueKey!(vT,kT)[] map;
map.length = freq_aa.keys.length;
size_t i = 0;

foreach( k,v ; freq_aa )
    map[i++] = ValueKey!(vT,kT)(v,k);

map.sort;

Note: not tested, but that should get you going in the right direction.

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/


More information about the Digitalmars-d-learn mailing list