'How to convert std::vector<std::pair<double, double>> dataVector to Eigen::MatrixXd rtData(dataVector.size(), 2)

Is there a fast way to make conversion below?

use "std::vector<std::pair<double, double>> dataVector" to initialize "Eigen::MatrixXd rtData(dataVector.size(), 2)"



Solution 1:[1]

Assuming sizeof(std::pair<int,int>) == 2*sizeof(int) (i.e., std::pair is not adding any padding) you can use an Eigen::Map of a row-major integer matrix, then cast it to double. Something like this:

typedef Eigen::Matrix<int, Eigen::Dynamic, 2, Eigen::RowMajor> MatrixX2i_r;
Eigen::MatrixXd rtData
    = Eigen::Map<MatrixX2i_r const>(&(dataVector[0].first), dataVector.size(), 2).cast<double>();

You can also use that expression directly without storing it into a MatrixXd (conversion will happen on the fly, every time the expression is used -- so if you use rtData multiple times, it could still be better to store it once).

Solution 2:[2]

I am assuming you wish to create a two column matrix from bunch of pairs stacked in a vector.

As far I can see in the documentation MatrixXd is typedef of Matrix<double,dynamic,dynamic> so first potential issue is that you wish to fill matrix of double by int values.

Since MatrixXd is merely a typedef I don't think there is a suitable constructor in Eigen library for you to do quick conversion.

Simply write a code or a function that iterates through your vector and populates the matrix. In C++14:

int itt=0;
for (const auto& [first, second] : dataVector)
{
   rtData(itt,0) = first;
   rtData(itt,1) = second;
   itt++;
}

That is a neat for loop that can go through vector of pairs, you still need the index of the elements, as Eigen matrices do not have push_back methods as STL. Note again that I would advise MatrixXi if you are populating it with integers and not doubles.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chtz
Solution 2 Aleksandar Demi?