如何用零填充3D数组

时间:2018-06-21 14:41:46

标签: c++ c++11 multidimensional-array segmentation-fault fill

我试图用零填充3d数组,以用std::fill“重置”数组中的所有元素。

使用2d数组,可以像这样使用std::fill函数:

float histogram2D[28][28] = {{0}};
//give the array some values here then trying to reset it with zeros.....
fill( &histogram2D[0][0], &histogram2D[0][0] + sizeof(histogram2D), 0 );

尝试使用std::fill函数用零填充3d数组不起作用,并且出现错误:分段错误(堆芯被丢弃)

float histogram3D[28][28][28] = {{{0}}};
//give the array some values here then trying to reset it with zeros.....
fill( &histogram3D[0][0][0], &histogram3D[0][0][0] + sizeof(histogram3D), 0 );

有没有人知道如何使用std::fill函数(甚至在3d数组中也可以使用)?

2 个答案:

答案 0 :(得分:4)

使用std::vector<>代替原始数组,这为您提供了一个连续的动态数组,因此,您不仅可以通过迭代器进行访问,还可以使用指向元素的常规指针的偏移量进行访问。此外,它具有填充构造器,通过它您可以很轻松地完成工作,如下所示。

#include <vector>
// following is a 28 x 28 x 28 matrix filled with 0s
std::vector< std::vector< std::vector<int> > > 
              histogram3D(28, std::vector< std::vector<int> >(28, std::vector<int>(28)) );

或使用std::vector::resize()

std::vector< std::vector< std::vector<int> > > histogram3D;
histogram3D.resize(28, std::vector< std::vector<int> >(28, std::vector<int>(28)) );

并填充其他内容:

histogram3D.resize(28, std::vector< std::vector<int> >(28, std::vector<int>(28, 2)) );
                                                                   mention here ^
// now you have filled with 2

或使用某些值填充特定的3D行,您可以再次使用std::fill

// fill the first row in [0][0]th location with all zeros
std::fill(histogram3D[0][0].begin(), histogram3D[0][0].end(), 0);

答案 1 :(得分:0)

将memset函数用作memset(histogram3D,0,sizeof(histogram3D));

相关问题