我需要在我的程序中使用特征矩阵的向量。矢量的大小是已知的。但是,对应于向量每个成员的矩阵大小可以具有不同的大小,并且需要动态分配。基于 https://eigen.tuxfamily.org/dox/group__TopicStlContainers.html 我想我可以将我的矩阵声明为
#define EIGEN_USE_MKL_ALL
#define EIGEN_USE_LAPACKE
// Additional libraries
#include <iomanip>
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <algorithm>
#include "Eigen/Core"
#include "Eigen/LU"
#include "Eigen/StdVector"
int A = 4;
int B = 5;
std::vector<Eigen::MatrixXd > inv_K_mat2(A,B);
这会导致编译期间出现以下错误
error C2664: 'std::vector<Eigen::MatrixXd,std::allocator<_Ty>>::vector(std::vector<_Ty,std::allocator<_Ty>> &&,const _Alloc &) noexcept(<expr>)': cannot convert argument 2 from 'int' to 'const _Alloc &'
1> with
1> [
1> _Ty=Eigen::MatrixXd,
1> _Alloc=std::allocator<Eigen::MatrixXd>
1> ]
1> and
1> [
1> _Alloc=std::allocator<Eigen::MatrixXd>
1> ]
1>e:userspkumaworkedem_flex_tireedem-deformable-tire-developcompilerpme_flextire_interface.cpp(107): note: Reason: cannot convert from 'int' to 'const _Alloc'
1> with
1> [
1> _Alloc=std::allocator<Eigen::MatrixXd>
1> ]
如果我将声明更改为
std::vector<Eigen::Matrix<double, 4, 5 > > inv_K_mat2;
有没有不同的方法来初始化特征矩阵的向量,其中大小可以动态分配?
为什么会出现此错误?
让我们看看你的代码:
std::vector<Eigen::MatrixXd> inv_K_mat2(A,B);
您正在尝试构造事物的std::vector
(在本例中为动态大小的特征矩阵(。但是没有std::vector
构造函数将两个整数作为参数。 有一些版本的构造函数(上面链接中的版本 (3( 和 (4( (将整数作为第一个参数 - 向量的初始大小 - 以及可选的第二个参数。
在版本(3(中,第二个参数是类型const T&
,即包含在向量中的类型:在我们的例子中它是MatrixXd
。您可以将整数B
转换为const MatrixXd&
吗?不。所以编译器看另一个候选者:构造函数版本(4(。
编译器假定第二个参数必须是分配器。您可以将int
转换为分配器吗?不。这是一个问题,这就是您收到的错误消息的含义:
cannot convert argument 2 from 'int' to 'const _Alloc &'
为什么你的第二个版本有效?
现在我们来看看下一个版本:
std::vector<Eigen::Matrix<double, 4, 5 > > inv_K_mat2;
在这种情况下,这是不同的。您正在构造一个不同类型的向量T
(这次是一个固定大小的 4×5 特征矩阵(,上面链接中的构造函数没有参数:版本 (1(。这很好,编译器很高兴。
请注意,在这种情况下,您构造的向量从空开始(它包含 0 个矩阵(。如果你想构造一个初始化为包含 42 个固定大小矩阵的向量,你会做这样的事情
std::vector<Eigen::Matrix<double, 4, 5 > > inv_K_mat2(42);
在这里,我们再次使用带有整数参数的构造函数版本 (3(。我们的向量从 42 个固定大小为 4×5 的矩阵开始。请注意,当然没有初始化矩阵的元素。但是我们的好朋友构造函数 (3( 允许我们提供类型const T&
的参数作为所有元素的初始值。所以这给了我们这样的东西:
std::vector<Eigen::Matrix<double, 4, 5>> inv_K_mat2(42, Eigen::Matrix<double, 4, 5>::Zero());
这将初始化一个包含 42 个固定大小的 4×5 矩阵的向量,全部设置为值Eigen::Matrix<double, 4, 5>::Zero()
(即 0 初始化的固定大小 4×5 矩阵(。
我们如何让它适用于动态矩阵?
我们将使用与此处固定大小矩阵相同的策略。关键的区别在于,对于MatrixXd
,我们需要在构造函数中指定大小MatrixXd
.因此std::vector
,我们将再次调用构造函数 (3(,将初始大小作为第一个参数,将大小为 4 和 5 的新构造MatrixXd
作为第二个参数。
std::vector<Eigen::MatrixXd> inv_K_mat2(42, Eigen::MatrixXd(4, 5));
或者,如果你想把所有的矩阵初始化为0,你可以使用MatrixXd
'零函数,它允许你构造一个任何给定大小的零矩阵作为参数:
std::vector<Eigen::MatrixXd> inv_K_mat2(42, Eigen::MatrixXd::Zero(4, 5));