Sorting structs?

Benjamin Thaut code at benjamin-thaut.de
Wed Jan 29 01:45:18 PST 2014


Am 29.01.2014 10:33, schrieb Boomerang:
> Hello everybody. I'm trying to learn D by solving simple
> exercises.
>
> The current exercise: read names and grades of students, then
> print the names of students in descending order of their grades.
>
> In C++, I would define a Student struct, overload the operators:
> bool operator<(const Student&, const Student&)
> std::istream& operator>>(std::istream&, Student&)
>
> Then I'd store the Students in let's say a std::vector, sort it
> in reverse, then print it accordingly.
>
> But I don't know how to do things in D. I'm reading Cehreli's
> book, so far I've only finished its first trinity (just before
> struct).
>
> I would appreciate it if you explained your approach and gave
> source code illustrating it. Thanks!

You can either overload the compare operator for the struct

struct bla
{
   int i;
   int opCmp(ref const(bla) rh)
   {
     if(this.i < rh.i)
       return -1;
     if(this.i > rh.i)
       return 1;
     return 0;
   }
}

or you could just pass a different compare less expression to sort

bla[] arrayToSort;
sort!"a.i < b.i"(arrayToSort);

You can also pass a lambda or any function as compare less function to 
sort:
sort!((a,b){return a.i < b.i;})(arrayToSort);


Kind Regards
Benjamin Thaut


More information about the Digitalmars-d-learn mailing list