本文介绍了我可以在C(++)中检查数组是否全为0(或false)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在C(++)中检查数组是否全为0(或false),而无需遍历/循环每个单个值并且不分配相同大小的新数组(以使用memcmp)吗?

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)?

我正在滥用一组布尔数组,以在运行时拥有任意大的bitset,并对其进行一些flipping

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

推荐答案

您可以使用以下条件:

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

很明显,在内部,这会遍历所有值.

Obviously, internally, this loops over all values.

另一种选择(实际上应该避免循环)是重写所有写访问函数,并跟踪true是否曾经被写到向量中.

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.

更新

李·赖安(Lie Ryan)在下面的评论中,基于相同原理,描述了一种更健壮的方法.

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

这篇关于我可以在C(++)中检查数组是否全为0(或false)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:36
查看更多