简体   繁体   中英

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. First I tried 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 .

Then I tried with fill_n , it showed buildup failed. it seems fill_n cannot do with 2d array.

So is there any fast way to make all the elements in a 2d array to a certain value? in C++?

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

Thanks @paddy for the answer. Actually fill_n does work. 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.

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. Say for 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. 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:

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.

sizeof(a) will give you the size of a pointer in byte, which will depend on the system it is running. On a 32 bit system or OS, it's 4 (32 bits = 4 bytes), on a 64 bits system/OS, it's 8.

to get the size of an int array of 3x4 elements, you should use sizeof(int)*(3*4).

So, you should use memset(a, 5, sizeof(int)*(3*4));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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