std::tie(a, b) = std::minmax(a, b);
I think this is intuitive code. Clean and understandable. Too bad it doesn\'t work as intended, as std::minmax temp
You can enforce this with a certain level of brevity as follows.
std::tie(a, b) = std::minmax(+a, +b);
std::cout << "a: " << a << ", b: " << b << '\n';
Explanation: the builtin unary plus operator, for the sake of symmetry with its unary minus sibling, returns its operand by value (it also performs the usual arithmetic conversions, but that doesn't apply to int
s). This means it has to create a temporary, even though this temporary is nothing but a copy of the operand. But for the usage of minmax
in this example, it's sufficient: swapping references here doesn't assign through anymore, because the references on the right hand side (the const int&
arguments passed to minmax
) don't refer to the same objects as those on the left hand side (inside the tuple
of references created by std::tie
).
The output is as desired:
a: 5, b: 7