【问题标题】:How to make the type of vector in struct determined by the user?如何使结构中的向量类型由用户确定?
【发布时间】:2021-12-10 15:20:01
【问题描述】:

我有这个结构,可以在整数矩阵上进行乘法、加法和减法。 现在我想让这个结构的用户确定矩阵的类型(即向量的类型),即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;
    }
};

【问题讨论】:

    标签: c++ templates struct types stdvector


    【解决方案1】:

    我想让这个结构的用户确定矩阵的类型(即向量的类型),即intdoublelong等。

    您可以将Martix 结构设为template struct

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

    现在你实例化一个Matrix

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多