The Happy Struct Sorting Accident
BCS
ao at pathlink.com
Fri Aug 24 07:17:29 PDT 2007
Reply to nobody,
> The Happy Struct Sorting Accident
>
> Sorting with struct overlays
>
> I was somewhat marveled to find a new (to me) device that is probably
> fairly unique to the D programming language. It is possible to sort
> arrays of structs with interesting results using "struct overlays" and
> the sort property of arrays.
>
> All that is required to sort an array of structs using any
> field in the struct as the key is an alternate struct whose data
> overlays the original struct's data and contains an overloaded
> opCmp operator written for that particular field.
> A fairly common example are (ID,Name,...) tuples:
>
This was proposed a week or so ago (but for sorting using a different order)
> struct IDName
> {
> int id;
> char[] name;
> /*
> Normal struct behavior, maybe another opCmp . . .
>
> */
> }
> You need one struct overlay per unique sort behavior:
>
thois would be a hair more robust
strutc SortStructBy(T, uint i)
{
T t;
int opCmp(T u)
{
return this.tupleof[i].opCmp(u.tupleof[i]);
}
}
alias SortByStruct!(IDName, 0) IDName_sortID;
alias SortByStruct!(IDName, 1) IDName_sortName;
BTW, all of this falls under the heading of "dirty hacks" that should only
be used when all else fails
> struct IDName_sortID
> {
> int id;
> char[] name;
> int opCmp(IDName_sortID that)
> {
> return (this.id < that.id) ? -1 : (this.id > that.id) ? 1
> : 0;
> }
> }
> struct IDName_sortName
> {
> int id;
> char[] name;
> int opCmp(IDName_sortName that)
> {
> return (this.name < that.name) ? -1 : (this.name >
> that.name) ? 1 : 0;
> }
> }
More information about the Digitalmars-d
mailing list