How to sort a 2D array by column

monarch_dodra via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 7 14:12:07 PDT 2014


On Saturday, 7 June 2014 at 20:47:31 UTC, katuday wrote:
> On Saturday, 7 June 2014 at 19:18:34 UTC, Chris Cain wrote:
>> On Saturday, 7 June 2014 at 19:14:01 UTC, Chris Cain wrote:
>>>> This is my attemot to create a compare object. But I don't 
>>>> know how to use it together with .sort member function
>>>
>>>
>>> Don't use the .sort property. Use std.algorithm.sort, which 
>>> has a "less" predicate (that should return a bool).
>>>
>>> http://dlang.org/phobos/std_algorithm.html#sort
>>
>> Also note that the examples use a string to define the 
>> predicate, but it accepts functions as well. Such as:
>>
>>    bool myCompareFunc(AType lhs, AType rhs)
>>    {
>>        return lhs.blah < rhs.blah;
>>    }
>>
>>    //...
>>    AType[] arr;
>>    //...
>>    arr.sort!myCompareFunc();
>
> I need an example if you don't mind. My sort function requires 
> columns numbers supplied at run-time
>
> This is how I defined my sort function
> bool compareRow(int[] columns, ref const Row lhs, ref const Row 
> rhs)
> {
>   bool ret = false;
>   for (auto i = 0; i < columns.length; ++i)
>   {
>     const auto currentColumn = columns[i];
>       if (lhs[currentColumn] < rhs[currentColumn] )
>         ret = true;
>       if (rhs[currentColumn] < lhs[currentColumn] )
> 	ret = false;
>    }
>    return ret;
> }

That function don't make no sense (to me): It'll just return the 
result of the last iteration.

It *looks* like you are trying to do a lexicographical 
comparison? You should just replace those "ret = XXX" with 
straight up "return XXX". The last "return ret" should be "return 
false" (I think)

> Calling sort like this does not compile
>
> sort!(compareRow)(sort_key,the_table);

You need to create a delegate that binds your sort key to have 
predicate that accepts exactly 2 arguments. A lambda will fill 
that role.

sort!((lhs, rhs)=>compareRow(sort_key, a, b))(the_table);
or (not tested) use std.functional's curry:
sort!(curry!(compareRow, sort_key))(the_table);


More information about the Digitalmars-d-learn mailing list