Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

c++ - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...