C++11 has function std::minmax_element
which returns a pair of values. This, however, is quite confusing to handle and read, and produces an extra, later useless variable to pollute the scope.
auto lhsMinmax = std::minmax_element(lhs.begin(), lhs.end()); int &lhsMin = *(lhsMinMax.first); int &lhsMax = *(lhsMinmax.second);
Is there a better way to do this? Something like:
int lhsMin; int lhsMax; std::make_pair<int&, int&>(lhsMin, lhsMax).swap( std::minmax_element(lhs.begin(), lhs.end()));
Returning multiple values from a function using Tuple and Pair in C++ In C or C++, we cannot return more than one value from a function.
In C or C++, we cannot return multiple values from a function directly.
You could however make something like an empty pair using Boost. Optional. Then you would either use a boost::optional<std::pair<...>> giving you the option of returning either a pair or an empty state or use std::pair<boost::optional<...>, boost::optional<...>> for a pair where either object could be empty.
A simple approach to use the return type is to return one value that contains several values. This can be a std::pair or std::tuple . To keep examples simple we'll use pair but everything that follows is also valid for std::tuples for more than two returned values.
With structured binding from C++17, you may directly do
auto [lhsMinIt, lhsMaxIt] = std::minmax_element(lhs.begin(), lhs.end());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With