sort error

bearophile bearophileHUGS at lycos.com
Fri Jun 28 08:11:26 PDT 2013


snow:

> http://dpaste.dzfl.pl/e391a268
>
> This code throws me a "Range Exception" in Algorithm.d.
>
> If I use a lower number of random vectors, like 100, the code 
> terminates. Also, if I delete the template instruction like 
> this :
>
> sort(individuals);
>
> I also don't get an exception. Does anybody know, why this is 
> the case?

If I replace your vector with a tuple (that defines automatically 
a lexicographic opCmp) the problem seems to disappear:


import std.stdio, std.random, std.array,
        std.algorithm, std.range, std.typecons;

alias Vector3D = Tuple!(double,"x", double,"y", double,"z");
alias Individual = Vector3D[];

Vector3D getFitness(in ref Individual individual) pure nothrow {
     return individual[0];
}

bool myComp(in Individual x, in Individual y)  {
     return x.getFitness > y.getFitness;
}

Vector3D[] initializeRandomVectors(in uint count) {
     Vector3D[] result;
     foreach (immutable i; 0 .. count)
         result ~= Vector3D(uniform(0.0, 11.0),
                            uniform(0.0, 11.0),
                            uniform(0.0, 11.0));
     return result;
}

Individual[] initializeRandomIndividuals()  {
     return 1000.iota.map!(_ => 10.initializeRandomVectors).array;
}

void main() {
     auto individuals =  initializeRandomIndividuals;
     individuals.sort!(myComp, SwapStrategy.stable);
     "finished".writeln;
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list