如何用零填充3D数组

Fra*_*ans 2 c++ segmentation-fault fill multidimensional-array c++11

我试图用零填充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 );
Run Code Online (Sandbox Code Playgroud)

尝试使用该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 );
Run Code Online (Sandbox Code Playgroud)

std::fill如果3D数组有可能使用函数,有人知道吗?

JeJ*_*eJo 5

使用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)) );
Run Code Online (Sandbox Code Playgroud)

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

std::vector< std::vector< std::vector<int> > > histogram3D;
histogram3D.resize(28, std::vector< std::vector<int> >(28, std::vector<int>(28)) );
Run Code Online (Sandbox Code Playgroud)

为了填充其他内容:

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

或使用某些值填充特定的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);
Run Code Online (Sandbox Code Playgroud)

  • Bjarne Stroustrup会接受这个答案。他在书中写道:不要使用原始数组,否则会遇到问题。取而代之的是使用向量,它的构建旨在支持原始数组无法执行或正在以危险方式执行的许多操作。 (2认同)