4

文档非常清楚地说明了如何使 a 适应std::vector张量对象。 https://xtensor.readthedocs.io/en/latest/adaptor.html

std::vector<double> v = {1., 2., 3., 4., 5., 6. };
std::vector<std::size_t> shape = { 2, 3 };
auto a1 = xt::adapt(v, shape);

但是你怎么能反过来呢?

xt::xarray<double> a2 = { { 1., 2., 3.} };
std::vector<double> a2vector = ?;
4

2 回答 2

2

您可以std::vector从迭代器构造 a 。对于您的示例:

std::vector<double> w(a1.begin(), a1.end());

完整的例子就变成了:

#include <vector>
#include <xtensor/xadapt.hpp>
#include <xtensor/xio.hpp>

int main()
{
    std::vector<double> v = {1., 2., 3., 4., 5., 6.};
    std::vector<std::size_t> shape = {2, 3};
    auto a1 = xt::adapt(v, shape);
    std::vector<double> w(a1.begin(), a1.end());
    return 0;
}

参考:

于 2020-04-05T11:04:34.560 回答
2

不幸的是, Tom de Geus 的回答不保持维度,因此将 转换xarray of shape {2, 3}vector of size 6. 在尝试构建嵌套向量以绘制 a xarraywith时,我跳过了这个问题matplotlibcpp。对我来说,事实证明,Eigen::Matrix..是一个更适合这个目的的类。对于二维情况,可以轻松地将 Eigen::Matrix 转换为嵌套的 std::vector。对于更高的维度,值得一看here

代码

转换xt::xarrayEigen::MatrixXf_nested std::vector

#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"
#include <Eigen/Dense>



//https://stackoverflow.com/questions/8443102/convert-eigen-matrix-to-c-array
Eigen::MatrixXf xarray_to_matrixXf(xt::xarray<float> arr)
{
      auto shape = arr.shape();
      int nrows = shape[0];
      int ncols = shape[1];

      Eigen::MatrixXf mat = Eigen::Map<Eigen::MatrixXf>(arr.data(), nrows, ncols);
      return mat;
}

// https://stackoverflow.com/a/29243033/7128154
std::vector<std::vector<float>> matrixXf2d_to_vector(Eigen::MatrixXf mat)
{
      std::vector<std::vector<float>> vec;

      for (int i=0; i<mat.rows(); ++i)
      {
          const float* begin = &mat.row(i).data()[0];
          vec.push_back(std::vector<float>(begin, begin+mat.cols()));
      }
      return vec;
}

// print a vector
// https://stackoverflow.com/a/31130991/7128154
template<typename T1>
std::ostream& operator <<( std::ostream& out, const std::vector<T1>& object )
{
      out << "[";
      if ( !object.empty() )
      {
          for(typename std::vector<T1>::const_iterator
              iter = object.begin();
              iter != --object.end();
              ++iter) {
                  out << *iter << ", ";
          }
          out << *--object.end();
      }
      out << "]";
      return out;
}


int main()
{
      xt::xarray<float> xArr {{nan(""), 9}, {5, -6}, {1, 77}};
      std::cout << "xt::xarray<float> xArr = \n" << xArr << std::endl;


      Eigen::MatrixXf eigMat = xarray_to_matrixXf(xArr);
      std::cout << "Eigen::MatrixXf eigMat = \n" << eigMat << std::endl;

      std::vector<std::vector<float>> vec = matrixXf2d_to_vector(eigMat);
      std::cout << "std::vector<std::vector<float>> vec = " << vec << std::endl;

      return 0;
}

输出

xt::xarray<float> xArr = 
{{nan.,   9.},
 {  5.,  -6.},
 {  1.,  77.}}
Eigen::MatrixXf eigMat = 
nan  -6
  9   1
  5  77
std::vector<std::vector<float>> vec = [[nan, 9], [9, 5], [5, -6]]
于 2020-06-24T14:43:42.323 回答