我正在尝试使用boost::multi_array为c++中的模板类编写一些与维度无关的代码(尽管如果其他容器/数据结构在这方面做得更好,我很乐意听到它)。
给定一个维度,我想遍历其他所有维度的整个范围,沿着所选维度返回1d视图。这是相当简单的,或者至少它看起来来自boost文档。
当数组的维度在编译时已知时,我不知道如何在数组的所有维度上迭代选定的维度。
有什么建议吗?
通常情况下,您可以使用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;
}