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

How to find the maximum value's variable name?

int a = 1;
int b = 2;
int c = 3;
int d = 4;

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

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

你需要使用一个array来代替这些变量,然后你会很容易找到最大元素。请参阅示例 here

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

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

注意:您不会获得持有最大值的变量,只会获得对变量(匿名)的引用。

您可以通过以下方式进行

#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 个变量,并且您不想使用数组路由(如果我们有很多变量,建议这样做)。您可以根据 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;
}