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/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01