调整boost :: multi_array匹配另一个

resizing boost::multi_array to match another

本文关键字:array 另一个 boost multi 调整      更新时间:2023-10-16

我需要将一个多_array大小调整到另一个大小。

在Blitz 中我只能做

arr1.resize(arr2.shape());

是否有类似长度的多_array解决方案?因为

arr1.resize(boost::extents[arr2.shape()[0]][arr2.shape()[1]]);

似乎有点长而艰巨。

您可以使用shape()成员。可悲的是,它不能直接用作ExtentList(它不能建模Collection概念),但很容易将其制成一个:

using MA = multi_array<double, 2>;
MA ma(extents[12][34]);
auto& ma_shape = reinterpret_cast<boost::array<size_t, MA::dimensionality> const&>(*ma.shape());

这样

// demo
std::cout << "[" << ma_shape[0] << "][" << ma_shape[1] << "]n";

打印[12][34]

现在,ma_shape可以直接用于重塑/调整另一个数组:

活在coliru

#include <boost/multi_array.hpp>
#include <iostream>
int main() {
    using namespace boost;
    using MA = multi_array<double, 2>;
    MA ma(extents[12][34]);
    auto& ma_shape = reinterpret_cast<boost::array<size_t, MA::dimensionality> const&>(*ma.shape());
    // demo
    std::cout << "[" << ma_shape[0] << "][" << ma_shape[1] << "]n";
    // resize
    MA other;
    assert(!std::equal(ma_shape.begin(), ma_shape.end(), other.shape()));
    other.resize(ma_shape);
    assert(std::equal(ma_shape.begin(), ma_shape.end(), other.shape()));
    // reshape
    other.resize(extents[1][12*34]);
    assert(!std::equal(ma_shape.begin(), ma_shape.end(), other.shape()));
    other.reshape(ma_shape);
    assert(std::equal(ma_shape.begin(), ma_shape.end(), other.shape()));
}

我认为这是对boost.multiarray的另一个监督。我写了一堆"效用"函数,这些功能允许呈现形状(尺寸),基本索引(例如,每个维度为0或1)和扩展(每个维度中的基本指数和大小)。

namespace boost{
template<class MultiArray>
detail::multi_array::extent_gen<MultiArray::dimensionality>
extension(MultiArray const& ma){ //this function is adapted from 
    typedef detail::multi_array::extent_gen<MultiArray::dimensionality> gen_type;
    gen_type ret;
    typedef typename gen_type::range range_type;
    for(int i=0; i != MultiArray::dimensionality; ++i)
        ret.ranges_[i] = range_type(ma.index_bases()[i], ma.index_bases()[i]+ma.shape()[i]);
    return ret;
}
}

后来用作:

boost::multi::array<double, 3> m(boost::multi::extents[3][4][5]);
boost::multi::array<double, 3> n(extension(m)); // n takes the extension (and shape) of m

(如果基本索引不是零,则它也有效。它也适用于视图和其他Multi_array-type类。)

相关文章: