简体   繁体   English

使二维数组中所有元素的快速方法在C ++中变为某些非零值

[英]fast way to make all elements in a 2d array becomes certain non-zero value in C++

Say I want to assign 5 to all the elements in a 2d array. 假设我要为2d数组中的所有元素分配5。 First I tried memset 首先我尝试了memset

int a[3][4];
memset(a, 5, sizeof a);

and

int a[3][4];
memset(a, 5, sizeof(a[0][0])*3*4);

But the same result is all the elements becomes 84215045 . 但是相同的结果是all the elements becomes 84215045

Then I tried with fill_n , it showed buildup failed. 然后我尝试使用fill_n ,它显示fill_n失败。 it seems fill_n cannot do with 2d array. 似乎fill_n无法处理2D数组。

So is there any fast way to make all the elements in a 2d array to a certain value? 那么,有没有一种快速的方法可以将2d数组中的所有元素设置为某个值? in C++? 在C ++中?

********************************************************************************
UPDATE

Thanks @paddy for the answer. 感谢@paddy的答案。 Actually fill_n does work. 实际上fill_n确实有效。 The way I used it is like this, which fails to build up with my compiler. 我的使用方式是这样的,无法使用我的编译器进行构建。

fill_n(a,3*4,5);

@paddy's answer is correct, we can use it in this way for a 2d array. @paddy的答案是正确的,我们可以将其用于二维数组。

fill_n(a[0],3*4,5); 

Then I tried a little more, I found we can actually use this to deal with a 3d array, but it should be like this. 然后我尝试了更多,我发现我们实际上可以使用它来处理3d数组,但是应该像这样。 Say for a[3][4][5] . a[3][4][5]

fill_n(a[0][0],3*4*5,5); 

Unfortunately, memset is only useful for setting every byte to a value. 不幸的是, memset仅在将每个字节设置为一个值时有用。 But that won't work when you want to set groups of bytes. 但这在您要设置字节组时不起作用。 Because of the memory layout of a 2D array, it's actually okay to use std::fill_n or std::fill from the first value: 由于2D数组的内存布局,从第一个值开始使用std::fill_nstd::fill实际上是可以的:

std::fill_n( a[0], 3 * 4, 5 );
std::fill( a[0], a[3], 5 );  // Note a[3] is one past the end of array.

Depending on your compiler, something like this might even be vectorized for even faster execution. 根据您的编译器的不同,类似的内容甚至可能被矢量化以更快地执行。 But even without that, you ought not to worry about speed -- std::fill is plenty fast. 但是即使没有这些,您也不必担心速度std::fill足够快。

sizeof(a) will give you the size of a pointer in byte, which will depend on the system it is running. sizeof(a)将为您提供指针的大小(以字节为单位),这取决于它正在运行的系统。 On a 32 bit system or OS, it's 4 (32 bits = 4 bytes), on a 64 bits system/OS, it's 8. 在32位系统或OS上为4(32位= 4字节),在64位系统/ OS上为8。

to get the size of an int array of 3x4 elements, you should use sizeof(int)*(3*4). 要获得3x4元素的int数组的大小,应使用sizeof(int)*(3 * 4)。

So, you should use memset(a, 5, sizeof(int)*(3*4)); 因此,您应该使用memset(a,5,sizeof(int)*(3 * 4));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM