How to sort a 2D array by column
katuday via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jun 7 13:47:30 PDT 2014
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;
}
Calling sort like this does not compile
sort!(compareRow)(sort_key,the_table);
More information about the Digitalmars-d-learn
mailing list