如何写一个'过布尔值for`环(false和true) [英] How to write a `for` loop over bool values (false and true)
问题描述
一个大多为乐趣/好奇的问题:如何编写C ++中的为
循环会遍历的两个值布尔
(即真正
和假
),只用行动与 BOOL
(即没有转换成其它类型的)?
A question mostly for fun/curiosity: how to write a for
loop in C++ that would iterate over two values of a bool
(i.e. true
and false
), using only operations with bool
(i.e. without conversions to other types)?
的背景是,我想检查有多少解决方案的公式存在像(A和和B)|| (B&安培;!&安培;!C&放大器;&安培;!D)==真
,并开始写类似为(布尔A = FALSE; ???; ++ A)为(布尔B = FALSE; ......)
等,但立即得到了由卡住???
- 即会产生什么的状态继续循环?当然,我重写它使用int和我也知道,做...而
循环的工作,但我得到了好奇,如果这是有史以来可能写出这样的为
循环?而且,由于SO似乎并不有一个答案,我决定问:)
The background is that I wanted to check how many solutions exists for an equation like (A && B) || (!B && !C && !D) == true
, and started to write something like for (bool A=false; ??? ; ++A) for (bool B=false; ...)
etc but immediately got stuck by ???
- i.e. what would be the condition to continue the loop? Of course I rewrote it to use int, and I also know that a do ... while
loop will work, but I got curious if it's ever possible to write such a for
loop? And since SO does not seem to have an answer, I decided to ask :)
更新:注意,显而易见的变种的(!布尔A = FALSE; A; A = TRUE)
中至少有两个现在已经删除的的答案建议只会运行一个迭代,因为第二个条件!A
变成假
和循环结束。
Update: note that an "obvious" variant for(bool A=false; !A; A=true)
suggested in at least two now-removed answers will only run one iteration, because for the second one the condition !A
becomes false
and the loop ends.
经过一番琢磨之后,我相信这是不可能做到这一点在C ++ 03没有迪特马尔库尔提出了第二个变量或基于指针的结构等。该条件应在所需执行测试三次,这样一个布尔值的两个值是不够的。而do-while循环工作,因为第一次迭代无条件执行,条件只有两次检查等一个布尔值可用于之间持续和退出。
After some pondering, I believe it's impossible to do it in C++03 without a second variable or a pointer based construct like suggested by Dietmar Kühl. The condition should be tested three times in a desired execution, so two values of a bool are simply not enough. And the do-while loop works because the first iteration is executed unconditionally, the condition is only checked twice and so a bool value can be used to select between continuing and exiting.
推荐答案
在C ++ 11:为(布尔乙:{假,真}){/ * ... * /}
结果
下面是一个C ++ 03版:
Here's a C++03 version:
for (bool a = true, b = false; b != a; a = a && b, b = !b) { /*...*/ }
(或者使用 A
或 B
)
这篇关于如何写一个'过布尔值for`环(false和true)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!