This thread suggest a way to copy the data of an Eigen::VectorXd
to a std::vector
However, I am wondering what can be the cleanest way to typecast/copy a two dimensional array into a std::vector<std::vector<double>>
CodePudding user response:
You could do the same as in the thread you shared, but do it for each column (default Eigen::ColMajor
) or row (Eigen::RowMajor
):
Eigen::MatrixXd mat(2,3);
mat << 1.1, 2.1, 3.1,
4.1, 5.1, 6.1;
std::vector<std::vector<double>> matrix(mat.cols());
auto ptr = mat.data();
for (auto& vec : matrix)
{
vec = std::vector<int>(ptr, ptr mat.rows());
ptr = mat.rows();
}
CodePudding user response:
One way might be using loop to traverse all the values of array, then store them in vector.
int ar[2][2];
vector<vector<int>> vec;
int main()
{
ar[0][0] = 1;
ar[0][1] = 2;
ar[1][0] = 3;
ar[1][1] = 4;
for(int i = 0; i < 2; i )
{
vector<int>v;
for(int j = 0; j < 2; j )
{
v.push_back(ar[i][j]);
}
vec.push_back(v);
}
for(int i = 0; i < vec.size(); i )
{
for(int j = 0; j < vec[i].size(); j ) cout<<vec[i][j]<<" ";
cout<<endl;
}
}
Another way: traverse each row and store them in vector.
int ar[2][2];
vector<vector<int>> vec;
int main()
{
int row = 2, col = 2;
ar[0][0] = 1;
ar[0][1] = 2;
ar[1][0] = 3;
ar[1][1] = 4;
for(int i = 0; i < row; i )
{
vector<int> currV = {vector<int> (begin(ar[i]), end(ar[i]))};
vec.push_back(currV);
}
for(int i = 0; i < vec.size(); i )
{
for(int j = 0; j < vec[i].size(); j ) cout<<vec[i][j]<<" ";
cout<<endl;
}
}