如何找到最大值的变量名?

How to find the maximum value's variable name?

本文关键字:变量名 最大值 何找      更新时间:2023-10-16
int a = 1;
int b = 2;
int c = 3;
int d = 4;

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

您需要使用array代替这些变量,然后您将很容易找到max元素。请看下面的例子

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

你可以这样做

#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

您可以应用可变的模板:

#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';
}
注意:您将无法获得持有最大值的变量,只能获得对变量的引用(匿名)。

如果仅限4个变量,并且您不想使用数组路由(如果我们有很多变量,建议使用数组路由)。您可以根据if-else语句使用下面的代码:

int max_of_four(int a, int b, int c, int d) {
    int max;
    if (a > b) {
        max = a;
    }
    else {
        max = b;
    }
    if (c > max) {
        max = c;
    }
    if (d > max) {
        max = d;
    }
    return max;
}