You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C++ struct结构体中vector的元素类型可由使用者自定义?

你可以通过C++的类模板实现类型可自定义的矩阵结构体,只需要给原有结构体添加模板参数,把所有硬编码的int类型替换成模板参数即可。

修改后完整代码

#include <vector>

// T为模板参数,代表矩阵元素的类型,支持int、double、long等满足四则运算的类型
template <typename T>
struct Matrix 
{
    std::vector<std::vector<T>> mat1, mat2;

    std::vector<std::vector<T>> mult()
    {
        std::vector<std::vector<T>> res(mat1.size(), std::vector<T>(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;
    }

    std::vector<std::vector<T>> add()
    {
        std::vector<std::vector<T>> res(mat1.size(), std::vector<T>(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;
    }

    std::vector<std::vector<T>> subtract() 
    {
        std::vector<std::vector<T>> res(mat1.size(), std::vector<T>(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;
    }
};

使用方法

使用时只需要在声明Matrix变量时指定元素类型即可:

// 元素为int类型的矩阵
Matrix<int> int_mat;
int_mat.mat1 = {{1,2},{3,4}};
int_mat.mat2 = {{5,6},{7,8}};
auto int_add_res = int_mat.add();

// 元素为double类型的矩阵
Matrix<double> double_mat;
double_mat.mat1 = {{1.1,2.2},{3.3,4.4}};
double_mat.mat2 = {{5.5,6.6},{7.7,8.8}};
auto double_mult_res = double_mat.mult();

// 元素为long类型的矩阵
Matrix<long> long_mat;

可选优化

你可以添加构造函数来直接初始化两个操作矩阵,简化使用流程:

template <typename T>
struct Matrix 
{
    std::vector<std::vector<T>> mat1, mat2;
    // 新增构造函数
    Matrix(std::vector<std::vector<T>> m1, std::vector<std::vector<T>> m2) : mat1(std::move(m1)), mat2(std::move(m2)) {}
    // 原有运算方法保持不变
    // ...
};

// 使用示例
Matrix<int> mat({{1,2},{3,4}}, {{5,6},{7,8}});
auto res = mat.subtract();

注意:类模板的实现代码需要放在头文件中,否则会出现链接错误。如果需要声明和实现分离,可以把实现部分放在后缀名为.hpp的头文件中,在声明的头文件末尾引入即可。

内容的提问来源于stack exchange,提问作者man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 12:57:02