【问题标题】:How to find the maximum value's variable name?如何找到最大值的变量名?
【发布时间】:2015-08-06 19:06:13
【问题描述】:
int a = 1;
int b = 2;
int c = 3;
int d = 4;

如何确定最大整数值是否存储在变量d 中?

【问题讨论】:

  • 听起来你想要一个数组 (std::array)。容器带有方便的算法,例如std::max_element
  • std::max({a,b,c,d}) 也可以,但除非你有充分的理由不使用数组,否则按 chris 所说的去做。

标签: c++ variables c++11 max


【解决方案1】:

您需要使用array 代替这些变量,然后您将轻松找到最大元素。见例子here

【讨论】:

  • 这是一个不正确的答案,因为问题是关于单独的变量。
  • 好吧,我只是建议一种更好的方法来使用多个值
【解决方案2】:

使用数组(而不是单个变量)并将数组索引报告为“答案”

【讨论】:

    【解决方案3】:

    你可以这样做

    #include <iostream>
    #include <algorithm>
    
    int main()
    {
        int a = 1;
        int b = 2;
        int c = 3;
        int d = 4;
    
        if ( std::max( { a, b, c, d } ) == d ) 
        {
            std::cout << "d contains the maximum equal to " << d << std::endl;
        }
    }    
    

    程序输出是

    d contains the maximum equal to 4
    

    【讨论】:

      【解决方案4】:

      您可以应用可变参数模板:

      #include <iostream>
      
      template <typename T, typename U, typename ... Args>
      T& max_ref(T&, U&, Args& ... );
      
      template <typename T, typename U>
      T& max_ref(T& t, U& u) {
          return t < u ? u : t;
      }
      template <typename T, typename U, typename ... Args>
      T& max_ref(T& t, U& u, Args& ... args) {
          return max_ref(t < u ? u : t, args ...);
      }
      
      int main()
      {
          int a = 1;
          int b = 2;
          int c = 3;
          int d = 4;
          max_ref(a, b, c, d) = 42;
          std::cout << d << '\n';
      }
      

      注意:你不会得到保持最大值的变量,只有一个对变量的引用(它是匿名的)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多