【问题标题】:multiple 'if...else...' statement in one line in c++C ++中一行中的多个'if ... else ...'语句
【发布时间】:2015-12-08 16:47:27
【问题描述】:

如果我想把这段代码写成一行怎么办?

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;
    }

我只是想知道这几行代码有什么捷径。

【问题讨论】:

  • 我建议使用 switch 语句来消除多个 if/else。
  • 字面意思是 return 1 值 1??
  • @devlincarnate:真的吗?怎么样??
  • @KarolyHorvath - Google switch 语句?例如:tutorialspoint.com/cplusplus/cpp_switch_statement.htm
  • @devlincarnate:如果您没有理解我评论的重点,请尝试使用开关编写此代码。我是认真的。

标签: c++ if-statement


【解决方案1】:

return ( count &gt;= 0 &amp;&amp; count &lt;= 799 ) ? (1 + count / 200) : 5;

即:如果 count 在范围内,则返回每个跨度 200 的连续值,如果超出范围,则返回 5。

【讨论】:

    【解决方案2】:

    如果您不能直接从 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 的性能相当。

    【讨论】:

      【解决方案3】:
      return 1 + std::min(count, 800) / 200;
      

      应该这样做。 if 隐藏在 std::min 中。如果count大于800,则替换为800,std::min(count, 800) / 200等于4。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-16
        • 2013-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多