Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

algorithm

max

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?

like image 989
gen Avatar asked Nov 29 '22 13:11

gen


1 Answers

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;
}
like image 165
masoud Avatar answered Dec 28 '22 23:12

masoud