多个"如果...否则...」C++ 中一行中的语句

multiple 'if...else...' statement in one line in c++

本文关键字:一行 语句 否则 如果 C++ 多个      更新时间:2023-10-16

如果我想把这些代码放在一行中,该怎么办?

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。