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

Eigen中BiCGSTAB线性求解器无法存入std::vector的问题求助

解决Eigen BiCGSTAB求解器无法存入std::vector的问题

Eigen的稀疏求解器(包括BiCGSTAB)继承自SparseSolverBase,该基类通过noncopyable禁用了拷贝构造与拷贝赋值操作;同时在Eigen 3.4版本中,这些求解器也未实现移动构造/赋值逻辑,因此直接将求解器对象存入std::vector会触发编译错误——无论是emplace_back还是std::move的方式都无法绕过这一限制。

解决方案:使用智能指针容器

通过存储求解器的智能指针(而非对象本身),可以避开对象拷贝/移动的限制。推荐使用std::unique_ptr(无所有权共享需求时)或std::shared_ptr(需共享所有权时),示例代码如下:

#include <Eigen/Eigen>
#include <vector>
#include <memory>

int main() {
    // 存储unique_ptr的vector
    std::vector<std::unique_ptr<Eigen::BiCGSTAB<Eigen::SparseMatrix<double>>>> solvers;

    // 方式1:直接在vector中构造新的求解器
    solvers.emplace_back(std::make_unique<Eigen::BiCGSTAB<Eigen::SparseMatrix<double>>>());

    // 方式2:先创建求解器再移动到vector中
    auto solver_ptr = std::make_unique<Eigen::BiCGSTAB<Eigen::SparseMatrix<double>>>();
    solvers.push_back(std::move(solver_ptr));

    // 使用求解器时通过指针访问
    // 示例:假设已有稀疏矩阵A和向量b
    // solvers[0]->compute(A);
    // Eigen::VectorXd x = solvers[0]->solve(b);
}

注意事项

  • 使用unique_ptr时,指针的所有权会被转移到vector中,原指针在std::move后会变为空,不可再使用。
  • 若需要多个地方共享求解器对象,可替换为std::shared_ptr,此时需用std::make_shared创建对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:25:18