Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check in C(++) if an array is all 0 (or false)?

Can I check in C(++) if an array is all 0 (or false) without iterating/looping over every single value and without allocating a new array of the same size (to use memcmp)?

I'm abusing an array of bools to have arbitrary large bitsets at runtime and do some bitflipping on it

like image 713
knittl Avatar asked Oct 28 '10 15:10

knittl


3 Answers

You can use the following condition:

(myvector.end() == std::find(myvector.begin(), myvector.end(), true))

Obviously, internally, this loops over all values.

The alternative (which really should avoid looping) is to override all write-access functions, and keep track of whether true has ever been written to your vector.

UPDATE

Lie Ryan's comments below describe a more robust method of doing this, based on the same principle.

like image 92
Oliver Charlesworth Avatar answered Sep 22 '22 00:09

Oliver Charlesworth


If it's not sorted, no. How would you plan on accomplishing that? You would need to inspect every element to see if it's 0 or not! memcmp, of course, would also check every element. It would just be much more expensive since it reads another array as well.

Of course, you can early-out as soon as you hit a non-0 element.

Your only option would be to use SIMD (which technically still checks every element, but using fewer instructions), but you generally don't do that in a generic array.

(Btw, my answer assumes that you have a simple static C/C++ array. If you can specify what kind of array you have, we could be more specific.)

like image 37
EboMike Avatar answered Sep 22 '22 00:09

EboMike


If you know that this is going to be a requirement, you could build a data structure consisting of an array (possibly dynamic) and a count or currently non-zero cells. Obviously the setting of cells must be abstracted through, but that is natural in c++ with overloading, and you can use an opaque type in c.

like image 27
dmckee --- ex-moderator kitten Avatar answered Sep 24 '22 00:09

dmckee --- ex-moderator kitten