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

如何将Eigen::Matrix的每一列转换为std::vector?

问题解决方案

错误原因

你触发静态断言的核心原因是Eigen::MatrixXf::Map生成的是二维矩阵类型的Map实例,你仅传入了行数参数没有指定列数,Eigen编译期校验判定你试图将矩阵对象作为向量调用,因此抛出静态断言错误。

最高效实现方案

Eigen的Map接口可以直接复用std::vector已分配的内存空间,无额外临时对象开销,时间复杂度为理论最优的O(行数×列数),实现代码如下:

场景1:需要存储所有列到vector数组

#include <Eigen/Dense>
#include <vector>

int main() {
    Eigen::MatrixXf mat(3, 4);
    mat << 1.1, 2, 3, 50,
           2.2, 2, 3, 50,
           3.1, 2, 3, 50;

    // 提前分配所有vector的内存
    std::vector<std::vector<float>> all_cols(mat.cols(), std::vector<float>(mat.rows()));
    for (int col = 0; col < mat.cols(); ++col) {
        // 直接映射vector内存为Eigen向量,赋值列数据
        Eigen::VectorXf::Map(all_cols[col].data(), mat.rows()) = mat.col(col);
    }
    return 0;
}

场景2:仅需逐个处理单列vector

std::vector<float> vec(mat.rows());
for (int col = 0; col < mat.cols(); ++col) {
    Eigen::VectorXf::Map(vec.data(), mat.rows()) = mat.col(col);
    // 此处直接处理当前列的vec即可
}

等价替代写法

由于Eigen默认采用列优先存储,单列的所有元素在内存中是连续排布的,也可以用memcpy实现相同效果,性能和Map写法完全一致:

std::memcpy(vec.data(), mat.col(col).data(), mat.rows() * sizeof(float));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:36:04