www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Templated Matrix class

reply Andrew Spott <andrew.spott gmail.com> writes:
So, I'm trying to create a matrix class that is templated, but I don't really
understand templates, so I don't know why this doesn't work.  Any idea why I
can't seem to do 2-D arrays?

-Andrew

module matrix;
private import std.string;

class Matrix(T) {
	private:
	T[][] ma;
	int nn;
	

	public:

	this() {
	}

	this(int n, int m) {
		ma[] = new T[m];
		ma = new T[n][m];
	}

	this(int n, int m, T a) {
		ma = new T[n][m];
		ma[][] = a;
	}

	T opIndex(int n, int m) {
		return ma[n][m];
	}

	void opIndexAssign(T)(T a, int n, int m) {
		ma[n][m] = a;
	}

	int rows() {
		return ma.length;
	}

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

	string toString() {
		if (ma.length == 0) return "[]";
		foreach (h; ma[0..$-1]) {
			string s = "[";
			foreach (k; h[0..$-1]) {
				s = std.string.format("%s, %s", s, k);
			}
			s = std.string.format("%s, %s]\n", s, h[$-1]);
    }
		return s;
	}

}
Apr 18 2009
parent bearophile <bearophileHUGS lycos.com> writes:
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
Apr 18 2009