Templated Matrix class

bearophile bearophileHUGS at lycos.com
Sat Apr 18 11:27:48 PDT 2009


import std.stdio: writefln;
import std.string: format;

class Matrix(T) {
    private T[][] m;

    this() {}

    this(int r, int c) {
        this.m = new T[][](r, c);
    }

    this(int r, int c, T x) {
        this.m = new T[][](r, c);
        foreach (ref row; this.m)
            row[] = x;
    }

    T opIndex(int r, int c) {
        return this.m[r][c];
    }

    void opIndexAssign(T)(T x, int r, int c) {
        this.m[r][c] = x;
    }

    int rows() {
        return this.m.length;
    }

    int cols() {
        return this.m[].length;
    }

    string toString() {
        // this isn't much efficient
        string result;
        foreach (row; this.m)
            result ~= format("%s\n", row);
        return result;
    }
}

void main() {
    auto m = new Matrix!(int)(10, 5);
    writefln(m);
    m[3, 2] = 1;
    writefln(m);
}

Bye,
bearophile



More information about the Digitalmars-d mailing list