gpt4 book ai didi

c++ - 遍历 boost::multi_array 的维度

转载 作者:太空狗 更新时间:2023-10-29 23:09:09 26 4
gpt4 key购买 nike

我正在尝试使用 boost::multi_array 在 C++ 中为模板类编写一些与维度无关的代码(尽管如果其他容器/数据结构在这方面做得更好,我很乐意听到它) .

给定一个维度,我想遍历所有其他维度的整个范围,返回沿所选维度的一维 View 。这相当简单,或者至少它看起来来自 boost 文档。

当数组的维度在编译时已知时,我不知道该怎么做是在数组的所有维度上迭代选定的维度。

关于如何做到这一点有什么建议吗?

最佳答案

通常您可以使用 boost::multi_array 来完成,下面是一些示例代码来创建 3D multi_array 的 2D View :

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

关于c++ - 遍历 boost::multi_array 的维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6434678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com