我正在尝试使用boost :: multi_array为c ++中的模板类编写一些与维度无关的代码(尽管如果其他容器/数据结构更好,我会很高兴听到它)
给定一个维度,我想迭代所有其他维度的整个范围,沿所选维度返回1d视图。这是相当简单的,或者至少它似乎来自增强文档。
在编译时已知数组的维度时,我无法弄清楚如何在数组的所有维度上迭代选定的维度。
有关如何执行此操作的建议吗?
答案 0 :(得分:1)
通常你可以用boost :: multi_array来做,下面是一些示例代码来创建3D multi_array的2D视图:
#include "boost/multi_array.hpp"
#include <cassert>
#include <iostream>
int main()
{
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type myArray3D(boost::extents[3][4][2]);
// Assign values to the elements
int values = 0;
for (index i = 0; i != 3; ++i)
{
for (index j = 0; j != 4; ++j)
{
for (index k = 0; k != 2; ++k)
{
myArray3D[i][j][k] = values++;
}
}
}
// Verify values
int verify = 0;
for (index i = 0; i != 3; ++i)
{
for (index j = 0; j != 4; ++j)
{
for (index k = 0; k != 2; ++k)
{
std::cout << "[" << i << "]";
std::cout << "[" << j << "]";
std::cout << "[" << k << "] = ";
std::cout << myArray3D[i][j][k] << std::endl;
assert(myArray3D[i][j][k] == verify++);
}
}
}
typedef boost::multi_array_types::index_range range;
array_type::index_gen indices;
// Create a new view with 2 dimentions fixing the 2nd dimention to 1
array_type::array_view<2>::type myView =
myArray3D[indices[range()][1][range()]];
std::size_t numDims = myView.size();
std::cout << "numDims = " << numDims << std::endl;
for (index i = 0; i != 3; ++i)
{
for (index j = 0; j != 2; ++j)
{
std::cout << "[" << i << "]";
std::cout << "[" << j << "] = ";
std::cout << myView[i][j] << std::endl;
}
}
return 0;
}