gen gen - 2 months ago 6
C++ Question

C++ Setting the larger of two variables to a new value

If I have two variables,

a
and
b
,
std::max(a,b)
returns the higher value.

Is it somehow possible to have this function modify whichever variable turns out to be greater, i.e. if
x
is a third variable,

max(a,b) = x;


such that after this call
a==x
holds if
a
was greater than
b
, else
b==x
?

Answer

Maybe you want this:

int &max(int &a, int &b)
{
    return a > b ? a : b;
}

Then:

int main()
{
    int x = 10, y = 20;
    max(x, y) = 100;
}

max will return a reference to the maximum number, then you can put your max function in the left hand of the assignment and change its value.

Template based version:

template<typename T>
T &max(T &a, T &b)
{
  return a > b ? a : b;
}