c++一次检查所有数组值
我想要做的是检查一个 bool 数组,看看其中是否有 3 个或更多已设置为 true。我能想到的唯一方法是对每个可能的组合使用 if 语句,其中有很多组合,因为有十个布尔值。有人对如何最好地做到这一点有任何建议吗?
what I want to do is check an array of bools to see if 3 or more of them have been set to true. The only way I can think to do this is using a if statement for each possible combination of which there is lots because there are ten bools. Dose anybody have any suggestions on how best to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这将是最简单的方法:
唯一的问题是即使找到 3 后它仍然继续计数。如果这是一个问题,那么我会使用 Sharptooth 的方法。
旁注
我决定以风格设计一种算法
std::all_of/any_of/none_of
对于我的个人库,也许您会发现它很有用:出于您的目的,您可以像这样使用它:
This would be the easiest way:
Only problem is it keeps counting even after it has found 3. If that is a problem, then I would use sharptooth's method.
side note
I've decided to fashion an algorithm in the style of
std::all_of/any_of/none_of
for my personal library, perhaps you will find it useful:For your purpose, you would use it like this:
更简单的方法是循环遍历数组:
The much easier way would be to loop through the array:
每当将数组元素设置为 TRUE 值时,都可以递增全局计数器。这将是最简单的方法。在代码中的任何一点,全局数组都会告诉您数组中 TRUE 元素的数量。
另一件事 - 如果您最多保留 32 个 bool 值,则可以使用单个 int 变量。 int 是 32 位(在 Win32 中),您可以存储 32 个 bool。
Whenever you are setting an array element into TRUE value, you can increment a global counter. This will be the simplest way. At any point in your code, the global array will tell you the number of TRUE elements in the Array.
Another thing - if you are keeping upto 32 bool values, you can use a single int variable. int is 32 bits (in Win32) and you can store 32 bool.
如果它是一个数组,您要做的就是循环它并计算 true 的数量。但恐怕你指的是某种位模式,对吧?
If it's an array, what you do is loop over it and count the number of trues. But I'm afraid you mean a bitpattern of some kind, right?
为什么不直接计算 true 的数量,然后在数量为 3 或更高时执行某些操作:
Why not just count the number of trues and then do something if the number is 3 or higher:
您可以循环遍历并构建数组的位掩码表示形式,然后可以并行比较最多
CHAR_BIT * sizeof (unsigned long)
:这假设您正在寻找 模式,不仅仅是想计算数组中
true
标志的数量。You can loop through and build a bit-mask representation of the array, then you can compare against up to
CHAR_BIT * sizeof (unsigned long)
in parallel:This assumes that you're looking for patterns, not just want to count the number of
true
flags in the array.只需循环遍历数组,计算设置为 true 的 bool 数量。
然后像这样称呼它
Just loop through the array counting the number of bools set to true.
Then call it like so
将布尔值存储为整数中的位。然后应用位调整技巧之一。
Store the bools as bits in an integer. Then apply one of the bit twiddling hacks.