Is there a nice way to assign std::minmax(a, b) to std::tie(a, b)?

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';


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.

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.

Leave a Comment