How to return two values ​​of a function?


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.

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