stdvectorxtensor

How to convert an xarray to std::vector?


The docs make it quite clear on how to adapt a std::vector to a tensor object. 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);

But how can you do it for the other way round?

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

Solution

  • You can construct a std::vector from iterators. For your example:

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

    The complete example then becomes:

    #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;
    }
    

    References: