Hi, I'm now crazing with memset() and fill() or fill_n(), in the Problem D Div3 Round #636, i used fill_n() and it was TLE, so I changed to memset() and accepted. I dont't understand the way memset work. Can you explain me ? Thank you
*In addition, sometimes i use memset but it doesn't work well Here are my submissions: TLE: https://codeforces.net/contest/1343/submission/77570494 Accepted: https://codeforces.net/contest/1343/submission/77570825
Put the link to the submission.
I have just updated the submissions links, sorry for the inconvenience
Auto comment: topic has been updated by NguyenDangQuan (previous revision, new revision, compare).
I also needed a little clarification with regard to how memset works, because doing something like
gives overflow. Can someone please help me with this explanation?
memset fills the entire array byte by byte. Thus filling with -2 means filling with 11111110 (2's complement form of -2). In case your array is a int array, each element is of 32 bits or 4 bytes. Hence, each array element will be filled with 11111110 11111110 11111110 11111110 which is -16843010 in decimal form which you have mistaken for overflow. So memset is used to fill only values like 0 (00000000) , -1(11111111) etc. Hope it helps.
Ok, thanks a lot!
memset
fills the arraybyte
bybyte
. Therefore if you do something like:memset(array, 1, sizeof(array))
, you will find that all elements of the array are NOT set to 1 but to $$$16843009 $$$ but instead if you usefill_n(array, N, 1)
, this will fill allelements
of the array with value $$$1$$$. I hope it helps!Thank you!
Yes, memset is sometimes faster. It's a more low-level byte thing, while fill is similar to the usual for-loop you'd write to set the values.