如何让用户确定struct中vector的类型?

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

我有这个结构可以对整数矩阵进行乘法、加法和减法运算。 现在我想制作由该结构的用户确定的矩阵类型(即向量类型),即 intdoublelong 等。

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;
    }
};

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..

您可以将 Martix 结构设为 template struct

template<typename T> 
struct Matrix 
{
    std::vector<std::vector<T>> mat1, mat2;

    // .... replace all your int with T
}

现在你实例化一个Matrixclass

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

旁注:Why is "using namespace std;" considered bad practice?