【问题标题】:How to dynamically set dimensionality for a boost multi_array如何为 boost multi_array 动态设置维度
【发布时间】:2017-01-31 14:25:57
【问题描述】:

我有一个函数需要创建一个 boost multi_array,其维度是先验未知的。但是,对于任何给定的维度,范围都是已知的。如何逐步为我的数组构建一个 extents 对象?

类似:

array_type::extent_gen<array_type::dimensionality> my_extents;
for (size_type d = 0; d < array_type::dimensionality; d++) {
    extents = extents[5];
}
array_type my_array(extents);

将一个尚未确定的数组设置为每个维度的范围为 5....

【问题讨论】:

  • extents = extents[5]; ?我不明白这应该是什么
  • 试图为 d 5s 获得类似“extents[5][5][5].....[5]”的东西
  • 考虑在问题中添加您想要实现的/what/(而不是/how/)。还要添加array_type的定义。

标签: c++ arrays boost


【解决方案1】:

我不认为你可以,因为 multi_array 的维度是在类型的模板参数中编码的:

typedef boost::multi_array<double, 3> array_type;

从根本上不同于

typedef boost::multi_array<double, 2> array_type;

你可能做的“最好”就是拥有

static const int MAX_DIMENSIONS = 10;
typedef boost::multi_array<double, MAX_DIMENSIONS> array_type;

然后构建范围以将“未使用”维度的范围留在1

Live On Coliru

#include <boost/multi_array.hpp>
#include <iostream>

static const int MAX_DIMENSIONS = 5;
typedef boost::multi_array<double, MAX_DIMENSIONS> array_type;

array_type make_array(int dims, int default_extent = 5) {
    boost::array<int, MAX_DIMENSIONS> exts = {};
    std::fill_n(exts.begin(), exts.size(), 1);
    std::fill_n(exts.begin(), dims, default_extent);

    return array_type(exts);
}

int main() {
    auto a = make_array(3);
    auto b = make_array(2);

    std::copy(a.shape(), a.shape() + a.dimensionality, std::ostream_iterator<size_t>(std::cout << "\na: ", " "));
    std::copy(b.shape(), b.shape() + b.dimensionality, std::ostream_iterator<size_t>(std::cout << "\nb: ", " "));
}

打印

a: 5 5 5 1 1 
b: 5 5 1 1 1 

【讨论】:

  • (请注意,您随后可以从该数组中获得一个数组视图,该数组会透明地隐藏未使用的维度,但是 - 再次 - 您将在那里获得不同的静态类型)
猜你喜欢
  • 2011-09-20
  • 1970-01-01
  • 2012-04-05
  • 2012-01-18
  • 2014-07-08
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多