多个"如果...否则...」C++ 中一行中的语句
multiple 'if...else...' statement in one line in c++
如果我想把这些代码放在一行中,该怎么办?
if (count >= 0 && count <= 199) {
return 1;
} else if (count >= 200 && count <= 399) {
return 2;
} else if (count >= 400 && count <= 599) {
return 3;
} else if (count >= 600 && count <= 799) {
return 4;
} else {
return 5;
}
我只是想知道这几行代码有没有捷径。
return ( count >= 0 && count <= 799 ) ? (1 + count / 200) : 5;
也就是说:如果计数在范围内,则为200的每个跨度返回连续值,如果计数超出范围,则返回5。
如果您不能直接根据Scott Hunter的答案中所示的计数计算范围(例如,如果范围大小不一致,或者它们映射到的值没有形成一个简单的模式),您可以封装一个类似的小表查找:
#include <algorithm>
#include <utility>
#include <vector>
int FindRange(int count) {
static const std::pair<int, int> ranges[] = {
{ 0, 5 },
{ 200, 1 },
{ 400, 2 },
{ 600, 3 },
{ 800, 4 }
};
const auto it = std::find_if(std::begin(ranges), std::end(ranges),
[=](const std::pair<const int, int> &range) {
return count < range.first;
});
return (it == std::end(ranges)) ? ranges[0].second : it->second;
}
然后,您可以更改表值,只要您对它们进行排序,此函数就会继续工作。
这是对表的线性搜索,因此它的性能应该与级联if-else的性能相当。
return 1 + std::min(count, 800) / 200;
应该这样做。if
隐藏在std::min
中。如果count
大于800,则将其替换为800,并且std::min(count, 800) / 200
等于4。
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 从C++dll访问C#中的一行主要参数
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- Insert函数不适用于2 if语句C++
- 在C++中,我如何接受不同于同一行的用户输入
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 防止 clang 格式将多行 if 语句折叠为一行
- 最后一行欧普特两个组合输出问题?如果其他语句
- 如果语句,可能是错误的,输入后不要移至下一行
- 多个"如果...否则...」C++ 中一行中的语句
- 循环在同一行上多次打印相同的语句