2

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.

Bill Hicks
  • 105
  • 1
  • 4
  • 15

4 Answers4

16

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).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1
typedef struct {
    int a, b;
} tuple;

tuple example() {
    tuple ret = {1, 2};
    return ret;
}
earl
  • 99
  • 4
1

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.

roottraveller
  • 7,942
  • 7
  • 60
  • 65
0

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.

Abu Hanifa
  • 2,857
  • 2
  • 22
  • 38