Last update July 30, 2009

Helmut Leitner /
Struct Sort



How to sort a struct. Built from a hint of WalterBright in NewsDmD, Apr 03. Linked from /Snippets.

The name for the TypeInfo? class

TypeInfo_S8ssort_As

seems to be built this way

  1. TypeInfo_S
  2. number of characters of the following three parts
  3. source file name (or module name?)
  4. _ (separator)
  5. struct name
but you don't need to construct it. You will get an error message from the linker when you use a "structname.sort" without providing a corresponding TypeInfo? class.


import std.stdio;

/*
** ssort.d (C) Helmut Leitner 2003
** struct sort example
** public domain
*/

struct As // a struct
{
    int x;
    string name;

    int cmp(As *p2)
    {
        int a = x;
        int b = p2.x;
        printf("compare %d %d\n",a,b);
        return a < b ? -1 : a > b ? 1 : 0;
    }
}

class TypeInfo_S8ssort_As : TypeInfo
{
    int tsize()
    {
        return As.sizeof;
    }

    int compare_name(void *p1, void *p2)
    {
        auto a = (cast(As *) p1).name;
        auto b = (cast(As *) p2).name;
        // printf("compare %.*s %.*s\n",a,b);
        return a < b ? -1 : a > b ? 1 : 0;
    }

    int compare_x(void *p1, void *p2)
    {
        int a = (cast(As *) p1).x;
        int b = (cast(As *) p2).x;
        // printf("compare %d %d\n",a,b);
        return a < b ? -1 : a > b ? 1 : 0;
    }

    int compare(void *p1, void *p2)
    {
        return compare_name(p1,p2);
    }
}

void AsPrint(As a) {
    printf("x=%d name=%.*s\n",a.x,a.name);
}

As sasar[3]= [      // static As array
    { 2, "Gamma"  },
    { 1, "Beta"   },
    { 3, "Alpha"  }
];

void AsArrayPrintTitle(As [] array, string title)
{
    if(title.length) {
        printf("%.*s",title);
    }
    for(int i=0; i<array.length; i++)
    {
        AsPrint(array[i]);
    }
}

int main()
{
    AsArrayPrintTitle(sasar,"\nbefore sorting:\n");
    sasar.sort;
    AsArrayPrintTitle(sasar,"\nafter sorting:\n");

    return (0);
}


FolderExamples
FrontPage | News | TestPage | MessageBoard | Search | Contributors | Folders | Index | Help | Preferences | Edit

Edit text of this page (date of last change: July 30, 2009 22:51 (diff))