Matrices using templates

I have to make a program in which I have to make matrices using class and templates in which user can give us the number of both rays and colums and we have to add, subtract and multiply those matrices. I'm allowed to use pointers too.
I'm new to C++ that's why i need some help.
You shouldn't have to use pointers for anything in this task.

What kind of access are you expected to provide? It's considerably simpler to offer operator() that takes two indices than making the m[x][y] syntax work.

Also, how is the user expected to give the number of rows and columns: at compile time, or at run time?

Here's a toy matrix class that takes rows and columns at runtime, uses operator() for access, and supports addition.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <valarray>

template<typename T>
class Matrix {
    std::valarray<T> data;
    size_t columns;
 public:
    Matrix(size_t rows, size_t columns)
    : data(rows*columns), columns(columns) {}

    T operator()(size_t row, size_t col) const
    {
        return data[row + columns*col];
    }

    T& operator()(size_t row, size_t col)
    {
        return data[row + columns*col];
    }

    Matrix& operator+=(const Matrix& other)
    {
        data += other.data;
        return *this;
    }
};

template<typename T>
Matrix<T> operator+(Matrix<T> lhs, const Matrix<T>& rhs)
{
    return lhs += rhs;
}

int main()
{
    Matrix<int> m1(2,2);
    m1(0,0) = 1; m1(0,1) = 2;
    m1(1,0) = 3; m1(1,1) = 4;

    Matrix<int> m2 = m1;
    Matrix<int> m3 = m1 + m2;

    std::cout << m3(0,0) << ' ' << m3(0,1) << '\n'
              << m3(1,0) << ' ' << m3(1,1) << '\n';
}

demo: http://ideone.com/ZR6xuV
Last edited on
Topic archived. No new replies allowed.