Classes and templates
Hefferman via Digitalmars-d
digitalmars-d at puremagic.com
Mon Oct 31 13:25:18 PDT 2016
On Monday, 31 October 2016 at 20:20:09 UTC, Meta wrote:
> [...]
>
> You can't use an un-instantiated template as a type anyway,
> unlike Java. There the above is illegal because of `BubbleSort
> b = ...`. The symbol BubbleSort by itself is not a type; you
> have to instantiate it with template arguments to create a
> type. So you *could* do it like this:
>
> BubbleSort!(typeof(arr)) b = new BubbleSort!(typeof(arr));
>
> But that's too verbose. There's need need to repeat ourselves.
> You can instead use `auto` and omit the type of `b`, which will
> be inferred from the right hand side:
>
> auto b = new BubbleSort!(typeof(arr));
Thanks! This compiled just fine...
[code]
import std.random;
import std.stdio;
void main()
{
immutable uint N = 10_000;
double[] arr = new double[](N);
for (uint k = 0; k < N; k++) arr[k] = uniform(0, N);
auto b = new BubbleSort!(typeof(arr));
b.Sort(arr);
}
public class BubbleSort(T)
{
private T[] a;
private uint n;
public void Sort(T)(T[] a) {
n = a.length;
bubblesort();
}
private void bubblesort() {
bool sorted;
do {
sorted = true;
for (uint k = 1; k < n; k++) {
if (a[k-1] > a[k]) {
T tmp = a[k];
a[k] = a[k+1];
a[k+1] = tmp;
sorted = false;
}
}
n--;
} while (!sorted);
}
}
[/code]
It gives a Range Violation upon executing, but I guess it's part
of the algorithm....
More information about the Digitalmars-d
mailing list