C++ 的 折叠表达式

等级 5477 次按键

C++17 折叠表达式把运算符应用到参数包的每个元素上:&& 检查是否全部为 true,|| 检查是否至少有一个为 true,逗号折叠则输出每个参数。bool 输出为 1 或 0。

C++ 代码

1template<typename... Args>
2bool allTrue(Args... args) {
// 展开为 args1 && args2 && ...:全部为 true 时才为 true
3 return (args && ...);
4}
5
6template<typename... Args>
7bool anyTrue(Args... args) {
// 用 || 展开:至少一个为 true 时为 true
8 return (args || ...);
9}
10
11template<typename... Args>
12void printAll(Args... args) {
// 逗号折叠:从左到右对每个参数执行 cout << arg << " "
13 ((cout << args << " "), ...);
14 cout << endl;
15}
16
// 全部为 true:输出“All true: 1”
17cout << "All true: " << allTrue(true, true, true) << endl;
// 有一个为 false:输出“All true: 0”
18cout << "All true: " << allTrue(true, false, true) << endl;
// 有一个为 true:输出“Any true: 1”
19cout << "Any true: " << anyTrue(false, true, false) << endl;
// 混合类型也可以:输出“1 2.5 hello x”
20printAll(1, 2.5, "hello", 'x');

运行结果

All true: 1
All true: 0
Any true: 1
1 2.5 hello x
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C++ 代码中需要输入的符号及其出现次数。

  • .× 28
  • <× 27
  • (× 11
  • )× 11
  • ,× 10
  • "× 10
  • ;× 8
  • :× 3
  • {× 3
  • }× 3

C++ 等级 5 的更多代码示例

← 返回 C++ 打字练习