我找到了以下代码来解决这个在线 C++ 编码问题:
“问题:编写一个程序,在不使用任何条件结构的情况下找到任意数组的最大元素:banned { if/if-else/switch/for/while/do/?:-operator }。”
# 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中我还没有见过这样的东西。 有人能解释一下我们如何让 boolean 表达式在没有 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)
为假,则调用 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 讨论的那样,您可以将任何类似的语句放在一行代码中。它只会被评估并立即被丢弃。
关于C++ 纯 boolean 表达式(没有 if、while 或其他语句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26638941/