How do I design a function prototype that would allow a single function to find and return simultaneously both the lowest and the highest values in an array? Thank you.
-
1Return a struct of two numbers, or an std::pair. – Andrew Cheong Jan 30 '16 at 05:05
-
Can use an array (eg. either pass the array to the function or defined globally). – roottraveller Jan 30 '16 at 05:07
-
Custom struct for return is messy. I prefer void func(int* low_out, int* high_out); – Inisheer Jan 30 '16 at 05:12
-
@rkm_Hodor: That only covers C; there are much better options in C++. – ShadowRanger Jan 30 '16 at 05:16
-
@Inisheer: Again, return through pointer is reasonable C idiom, but terrible C++ code. – ShadowRanger Jan 30 '16 at 05:17
-
@ShadowRanger Yup. That's why it's left in the comments... and why I stick with C ;) – Inisheer Jan 30 '16 at 05:17
4 Answers
std::pair
covers returning two values, std::tuple
generalizes to any number of values. And with std::tuple
's std::tie
utility function, the caller can receive the results into separate variables too, avoiding the need to extract them one by one, for example:
std::tuple<int, int> returns_two()
{
return std::make_tuple(1, -1);
}
int main() {
int a, b;
std::tie(a, b) = returns_two();
// a and b are now 1 and -1, no need to work with std::tuple accessors
std::cout << "A" << a << std::endl;
}
Of course, in this case, you don't actually need to roll your own code to return the min and max of an input because there is a templated utility function that already does this, std::minmax
(for two discrete args and initializer lists) and std::minmax_element
(for ranges defined by iterators) (which both return std::pair
, and std::pair
is fully compatible with std::tuple
of two elements).

- 143,180
- 12
- 188
- 271
typedef struct {
int a, b;
} tuple;
tuple example() {
tuple ret = {1, 2};
return ret;
}

- 99
- 4
-
-
This is the C solution, but it reinvents the wheel when C++ utility containers can do the same job without defining your own custom types explicitly. – ShadowRanger Jan 30 '16 at 05:18
There are three possible scenario..
Method 1 is using global array.
Method 2 is using pointer.
Method 3 is using structure.
You can't return multiple values from a C++ function by using variables. You can return only a data structure with multiple values, like a struct or an array.

- 7,942
- 7
- 60
- 65
use stl pair data type
for return two value or user define struct data type
for return more value from a function.
Or you can return array from a function for multiple value.
There are so many ways.

- 2,857
- 2
- 22
- 38