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

时间:2015-08-06 19:06:13

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

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

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

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

您需要使用array代替这些变量,然后您才能轻松找到max element。请参阅示例here

答案 2 :(得分:2)

您可以通过以下方式执行此操作

#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

答案 3 :(得分:1)

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

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

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