C++Bare布尔表达式(不包含if、while或其他语句)
C++ Bare Boolean Expressions (without an if, while or some other statement)
我发现以下代码可以解决这个在线C++编码问题:
"问题:编写一个程序,在不使用任何条件结构的情况下找到任意数组中最大的元素:禁止{if/if-else/switch/for/while/do/?:-运算符}。"
# include <iostream>
int findMax(int * array, size_t size)
{
int max, other;
size > 2 && (other = findMax(array + 1, size - 1)) || (other = array[1]);
other > array[0] && (max = other) || (max = array[0]);
return max;
}
int main()
{
int array[] = {3, 1, 4, 15, 9, 2, 6, 5, 35, 8, 97, 93, 23, 84, 62, 64, 33, 83, 27, 950, 28, 841, 971, 69, 39, 937, 510};
std::cout << findMax(array, sizeof(array) / sizeof(array[0])) << std::endl;
return 0;
}
我的问题:我们如何在C++中做这样的事情?
size > 2 && (other = findMax(array + 1, size - 1)) || (other = array[1]);
我在C++方面的经验有限,在java中还没有见过这样的东西。有人能解释一下我们如何在没有if、while或其他语句的情况下让布尔表达式裸运行吗。我在谷歌上搜索了很多,但找不到任何有用的东西。非常感谢。
编辑:谢谢大家的回复。我理解短路的概念。但通常我会这样使用它:
1. if (boolean1 && boolean2 || boolean3)
2. // do sth;
3. while(boolean1 || boolean2)
4. // loop;
5. return boolean1 && boolean2;
现在我更像是一个java用户。所以我在java代码中尝试了如下操作:
size > 2 && (other = findMax(array + 1, size - 1)) || (other = array[1]);
但它只是给出了一个编译时错误。我想java在这些规则上更严格。不管怎样,再次感谢。
这叫做短路。http://en.wikipedia.org/wiki/Short-circuit_evaluation
基本上,如果您有一个&&
或||
运算符,如果在检查下一个值时没有意义,它就永远不会执行。
考虑以下语句:
isCondition1Fulfilled(a) || isCondition2Fulfilled(a)
如果isCondition1Fulfilled(a)
为真,那么不管怎样,整个表达式都为真,所以调用isCondition2Fulfilled(a)
只是浪费时间。所以它从来没有被调用过。
这是另一个:
isCondition3Fulfilled(a) && isCondition4Fulfilled(a)
如果isCondition3Fulfilled(a)
为false,则调用isCondition4Fulfilled(a)
没有意义
你的程序利用了它,例如:
size > 2 && (other = findMax(array + 1, size - 1)) || (other = array[1]);
如果size
小于或等于2,则从不调用其余部分。如果不是,但findMax(array + 1, size - 1)
是正的,则不调用(other = array[1])
。
剩下的自己想:)
EDIT(对OP中EDIT的响应):
在这种情况下,Java确实要严格得多。在C/C++中,几乎任何东西都可以进入if语句:int、指针、字符串、常量、char等。但正如我们与@Keith Thompson讨论的那样,您可以将任何类似的语句放在一行代码中。它将被评估并立即丢弃。
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- while循环中while循环的时间复杂度是多少
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 在其他文件中创建类时在 c++ 项目中不起作用
- 擦除while循环中迭代的元素
- 类与私有变量的其他类之间的线程安全性
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 为什么我的 while 循环对于特定输入中断,而对于其他输入工作正常?
- 如何引用或调用在 c++ 中的其他 while 循环中创建的向量?
- 从while循环(c++)中断后,似乎没有其他代码执行
- 如何停止 while 循环并转到我的其他语句
- C++Bare布尔表达式(不包含if、while或其他语句)
- 这个 while 循环执行其适当的功能,但对于其他内容是必需的