How to write a `for` loop over bool values (false and true)(如何在 bool 值上编写 `for` 循环(false 和 true))
问题描述
一个主要是为了好玩/好奇的问题:如何在 C++ 中编写一个 for 循环来迭代 bool 的两个值(即 true 和 false),仅使用 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) == true,然后开始写类似 for (bool A=false; ??? ; ++A) for (bool B=false; ...) 等,但立即被 ??? 卡住 - 即继续循环的条件是什么?当然,我将它改写为使用 int,而且我也知道 do ... while 循环会起作用,但是我很好奇是否有可能编写这样的 for 循环?由于 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 :)
更新:请注意,在至少两个现已删除的答案中建议的明显"变体 for(bool A=false; !A; A=true) 只会运行一次迭代,因为对于第二个条件 !A 变为 false 并且循环结束.
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.
经过深思熟虑后,我相信在没有第二个变量或像 Dietmar Kühl 建议的基于指针的构造的情况下,在 C++03 中是不可能做到的.条件应在所需的执行中测试 3 次,因此布尔值的两个值根本不够.do-while 循环之所以有效,是因为第一次迭代是无条件执行的,条件只检查两次,因此可以使用 bool 值在继续和退出之间进行选择.
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: for (bool b : { false, true }) {/* ... *
本文标题为:如何在 bool 值上编写 `for` 循环(false 和 true)
				
        
 
            
        基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				