Search code examples
c++templatesstructtypesstdvector

How to make the type of vector in struct determined by the user?


I have this struct that makes multiplication, addition, and subtraction on a matrix of integers. Now I want to make the type of matrix (i.e. the type of vectors) determined by the user of this struct i.e. int, double, long, etc..

struct Matrix 
{
    vector<vector<int>> mat1, mat2;

    vector<vector<int>> mult()
    {
        vector<vector<int>> res(mat1.size(), vector<int>(mat2.back().size()));
        for (int r1 = 0; r1 < mat1.size(); ++r1) {
            for (int c2 = 0; c2 < mat2.back().size(); ++c2) {
                for (int r2 = 0; r2 < mat2.size(); ++r2) {
                    res[r1][c2] += mat1[r1][r2] * mat2[r2][c2];
                }
            }
        }
        return res;
    }

    vector<vector<int>> add()
    {
        vector<vector<int>> res(mat1.size(), vector<int>(mat1.back().size()));
        for (int i = 0; i < mat1.size(); ++i) {
            for (int j = 0; j < mat1.back().size(); ++j) {
                res[i][j] = mat1[i][j] + mat2[i][j];
            }
        }
        return res;
    }

    vector<vector<int>> subtract() 
    {
        vector<vector<int>> res(mat1.size(), vector<int>(mat1.back().size()));
        for (int i = 0; i < mat1.size(); ++i) {
            for (int j = 0; j < mat1.back().size(); ++j) {
                res[i][j] = mat1[i][j] - mat2[i][j];
            }
        }
        return res;
    }
};

Solution

  • I want to make the type of matrix (i.e. the type of vectors) determined by the user of this struct i.e. int, double, long, etc..

    You can make your Martix struct to be a template struct

    template<typename T> 
    struct Matrix 
    {
        std::vector<std::vector<T>> mat1, mat2;
    
        // .... replace all your int with T
    }
    

    Now you instantiate a Matrix class

    Matrix<int> mat1;    // for integers
    Matrix<long> mat2;   // for long
    Matrix<double> mat3; // for doubles
    

    As a side notes: Why is "using namespace std;" considered bad practice?