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 use an initializer list for minmax
:
std::tie(a, b) = std::minmax({a, b});
This causes temporary objects to be created, just like when using unary plus, but has the benefit that it works with types lacking the unary plus operator too.
using namespace std::string_view_literals;
auto [a, b] = std::make_pair("foo"sv, "bar"sv);
std::tie(a, b) = std::minmax({a, b});
std::cout << "a: " << a << ", b: " << b << '\n';
Output:
a: bar, b: foo
Could it be that this is the wrong direction and just saying
if (a >= b) { std::swap(a, b); }
would be the best approach here?
I'd make it if(b < a) std::swap(a, b);
because of the Compare1 requirement, but yes, I suspect that'll be faster and it's still very clear what you want to accomplish.
[1] Compare [...] The return value of the function call operation applied to an object of a type satisfying Compare, when contextually converted to bool, yields true if the first argument of the call appears before the second in the strict weak ordering relation induced by this type, and false otherwise.