Is there a way to easily handle functions returning std::pairs?
With structured binding from C++17, you may directly do
auto [lhsMinIt, lhsMaxIt] = std::minmax_element(lhs.begin(), lhs.end());
To avoid polluting your scope, you could enclose the assignment in a smaller scope:
int lhsMin, lhsMax;
{
auto it = std::minmax_element(lhs.begin(), lhs.end());
lhsMin = *it.first;
lhsMax = *it.second;
}
alternatively, you can use a lambda
int lhsMin, lhsMax;
std::tie(lhsMin, lhsMax) = [&]{
auto it = std::minmax_element(lhs.begin(), lhs.end());
return std::make_tuple(*it.first, *it.second);
}();
This looks like enough of a common case to prompt a helper function:
template <class T, std::size_t...Idx>
auto deref_impl(T &&tuple, std::index_sequence<Idx...>) {
return std::tuple<decltype(*std::get<Idx>(std::forward<T>(tuple)))...>(*std::get<Idx>(std::forward<T>(tuple))...);
}
template <class T>
auto deref(T &&tuple)
-> decltype(deref_impl(std::forward<T>(tuple), std::make_index_sequence<std::tuple_size<std::remove_reference_t<T>>::value>{})) {
return deref_impl(std::forward<T>(tuple), std::make_index_sequence<std::tuple_size<std::remove_reference_t<T>>::value>{});
}
// ...
int lhsMin;
int lhsMax;
std::tie(lhsMin,lhsMax) = deref(std::minmax_element(lhs.begin(), lhs.end()));
index_sequence
is C++14, but a full implementation can be made in C++11.
Note: I'd keep the repeated decltype
in deref
's return type even in C++14, so that SFINAE can apply.
See it live on Coliru