如何找到最大值的变量名?
How to find the maximum value's variable name?
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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 使用指针从C++中的数组中获取最大值
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二维数组中查找最小值和最大值?
- 整数溢出,最大值为 pow(10,19)
- 以C++递归方式查找向量中的最大值
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 如何使用可变参数模板类使用模板元编程获得最大值
- C++不同的最小最大值实现
- Vec3b:r/g/b 颜色的最大值为 254,而不是 255
- 从模板继承<类型名 T、T 最大值、T 最小值>具有多个类型名模板参数的结构
- 当变量达到最大值时,unsigned int的增量是否会导致未定义的行为
- 返回变量绝对最大值的实际值
- 求外部变量的最大值
- c++中查找某些变量的平均值、最大值和循环计数的问题
- 如何找到最大值的变量名?