Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何找到最大值的变量名?_C++_Variables_C++11_Max - Fatal编程技术网

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

C++ 如何找到最大值的变量名?,c++,variables,c++11,max,C++,Variables,C++11,Max,如何确定最大整数值是否存储在变量d中?使用数组而不是单个变量,并报告数组索引作为答案如果需要使用数组而不是这些变量,则可以轻松找到max元素。参见示例您可以应用可变模板: int a = 1; int b = 2; int c = 3; int d = 4; 注意:您不会得到包含最大值的变量,只会得到对匿名变量的引用。您可以通过以下方式进行操作 #include <iostream> template <typename T, typename U, typename ..

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

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

如果需要使用数组而不是这些变量,则可以轻松找到max元素。参见示例

您可以应用可变模板:

int a = 1;
int b = 2;
int c = 3;
int d = 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';
}

听起来您需要一个数组std::array。容器带有像std::max_element这样的简便算法。std::max{a,b,c,d}也可以工作,但是按照chris说的去做,除非你有充分的理由不使用数组。这是一个错误的答案,因为问题是关于单独的变量。我只是想建议一种更好的方法来使用一些值
#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