在使用者@JoachimPileborg和@GeorgSchölly在他们的答案,其功能可被使用来重新初始化一个数组已解释。但是,我想添加一些示例代码并解释std::fill()和memset()之间的差异。
我假设你要(重新)初始化为0。您的阵列在这种情况下,你可以做到这一点,如下面的代码所示:
#include // For std::fill().
int main(int argc, char* argv[])
{
const int x = 2;
const int y = 3;
const int z = 5;
const int arraySize = x * y * z;
// Initialize array with 0.
int ID[x][y][z] = {};
// Use the array...
// Either reinitialize array with 0 using std::fill()...
std::fill(&ID[0][0][0], &ID[0][0][0] + arraySize, 0);
// ...or reinitialize array with 0 using memset().
memset(&ID[0][0][0], 0, sizeof(ID));
// Reuse the array...
return 0;
}
不过,如果你想使用的初始化数组另一值(例如,1),则必须要知道std::fill()和memset()之间一个重要的区别的:该功能std::fill()套您的阵列为指定的值的每个元素。相反,函数memset()将您的数组的每个字节设置为指定的值。这就是为什么memset()将数组大小作为字节数(sizeof(ID))。
如果初始化为0的阵列,这种差异不会导致出现问题。 但是,如果你想你的阵列中的每个元素初始化为一个非零值,那么你必须使用std::fill(),因为memset()会产生错误的结果。
让我们假设你想你的数组的所有元素设置为1,然后将下面的代码行会产生预期的结果:
std::fill(&ID[0][0][0], &ID[0][0][0] + arraySize, 1);
但是,如果以下列方式使用memset(),那么你得到了不同的结果:
memset(&ID[0][0][0], 1, sizeof(ID));
如上所述,这行代码的每一个字节设置为1。因此,你的阵列的每个整数元素将被设置为16843009,因为这等于十六进制值0x01010101。