如何转换矢量的STL矢量到犰狳垫

How to convert STL vector of vector to armadillo mat?

本文关键字:STL 何转换 转换      更新时间:2023-10-16

给定vector<vector<double > > A_STL,我想把它转换成arma::mat A

一种简单的方法是将向量矩阵的向量平坦化为一维向量。因此,您可以使用mat(std::vector)构造函数。

代码示例(未测试):
// Flatten your A_STL into A_flat
std::vector<double> A_flat;
for (auto vec : A_STL) {
  for (auto el : vec) {
    A_flat.push_back(el);
  }
}
// Create your Armadillo matrix A
mat A(A_flat);

注意向量的向量排序。

下面几行应该可以完成这项工作:

template<typename T>
arma::Mat<T> convertNestedStdVectorToArmadilloMatrix(const std::vector<std::vector<T>> &V) {
    arma::Mat<T> A(V.size(), V[0].size());
    for (unsigned_t i{}; i < V.size(); ++i) {
        A.row(i) = arma::conv_to< arma::Row<T> >::from(V[i]);
    }
    return A;
}
测试:

std::vector<std::vector<float_type>> vec = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}};
arma::Mat<float_type> mat = convertNestedStdVectorToArmadilloMatrix(vec);