C++ 如何找到最大值的变量名?
如何确定最大整数值是否存储在变量d中?使用数组而不是单个变量,并报告数组索引作为答案如果需要使用数组而不是这些变量,则可以轻松找到max元素。参见示例您可以应用可变模板: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 ..
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