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

如何将C++的vector<vector<double>>优雅转换为Eigen MatrixXd矩阵?

编译报错原因

Eigen的MatrixXd类型未提供直接接受std::vector<std::vector<double>>作为入参的构造函数,因此直接初始化会触发构造函数匹配失败的编译错误。

优雅实现方案

我们可以封装一个通用转换函数,实现和Pythonnumpy.array类似的调用体验,同时保证转换效率:

转换函数实现

#include <Eigen/Dense>
#include <vector>
#include <stdexcept> // 可选,用于异常校验

using Eigen::MatrixXd;

MatrixXd vector2d_to_eigen(const std::vector<std::vector<double>>& vec) {
    // 空输入直接返回空矩阵
    if (vec.empty()) {
        return MatrixXd(0, 0);
    }
    int rows = static_cast<int>(vec.size());
    int cols = static_cast<int>(vec[0].size());
    MatrixXd mat(rows, cols);

    // 可选:校验所有行长度一致,不符合则抛出异常
    for (const auto& row : vec) {
        if (static_cast<int>(row.size()) != cols) {
            throw std::invalid_argument("All rows must have the same length");
        }
    }

    // 按行映射赋值,避免逐元素拷贝,性能更优
    for (int i = 0; i < rows; ++i) {
        mat.row(i) = Eigen::Map<const Eigen::VectorXd>(vec[i].data(), cols);
    }
    return mat;
}

调用示例

将原代码中的构造语句替换为函数调用即可:

int main(int argc, char**argv) {
    std::vector<double> row1 = {  1.0,  2.0,  3.0,  4.0,  5.0 };
    std::vector<double> row2 = { 11.0, 12.0, 13.0, 14.0, 15.0 };
    std::vector<double> row3 = { 21.0, 22.0, 23.0, 24.0, 25.0 };

    std::vector<std::vector<double>> vv;
    vv.push_back(row1);
    vv.push_back(row2);
    vv.push_back(row3);

    MatrixXd mymatrix = vector2d_to_eigen(vv);
    return 0;
}
注意事项
  • 默认Eigen矩阵为列优先存储,上述实现按行赋值保证了数据顺序和嵌套vector的存储顺序完全一致
  • 如果你使用行优先的Eigen矩阵(Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>),可以直接将所有元素拼接为一维数组后用Eigen::Map一次性映射,性能会更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:00:01