Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to easily handle functions returning std::pairs?

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())); 
like image 641
Adam Hunyadi Avatar asked Oct 27 '16 11:10

Adam Hunyadi


People also ask

Can you return a pair C++?

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.

Can a function return 2 values in C++?

In C or C++, we cannot return multiple values from a function directly.

How do you return an empty pair in C++?

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.

What is the return type of pair?

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.


1 Answers

With structured binding from C++17, you may directly do

auto [lhsMinIt, lhsMaxIt] = std::minmax_element(lhs.begin(), lhs.end()); 
like image 153
Jarod42 Avatar answered Sep 24 '22 19:09

Jarod42