C++: Three results through references

Write one function that hands back three answers at once.

What to build

A function stats that finds the smallest number, the largest number and the mean in a single pass.

Requirements

  • Declare it as void stats(const vector<int>& v, int& lo, int& hi, double& mean).
  • Fill in all three results through the reference parameters.
  • Print min, max and mean, with the mean to two decimals.

Input

The first line has n. The second line has the n numbers.

Output

min X max Y mean Z

Constraints

1 ≤ n ≤ 1000, and each number is from -1000 to 1000.

Example

Input:

5
3 9 -2 5 1

Output:

min -2 max 9 mean 3.20

Why it works

Reference parameters are the caller's own variables, so the function can set all three. The const reference lets it read the whole vector without making a copy.

Examples

Example 1 · Input
5
3 9 -2 5 1
Expected output
min -2 max 9 mean 3.20
Example 2 · Input
1
7
Expected output
min 7 max 7 mean 7.00

Hints

Hint 1

A function can only return one value, but it can fill in several reference parameters.

Hint 2

Take the numbers as `const vector<int>&`, so they are read without being copied.

Hint 3

Work out the mean as a `double`, and print it with `fixed` and `setprecision(2)`.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;

void stats(const vector<int>& v, int& lo, int& hi, double& mean) {
    lo = v[0];
    hi = v[0];
    long long sum = 0;
    for (int x : v) {
        if (x < lo) lo = x;
        if (x > hi) hi = x;
        sum += x;
    }
    mean = (double)sum / v.size();
}

int main() {
    int n;
    cin >> n;
    vector<int> v(n);
    for (int i = 0; i < n; i++) cin >> v[i];
    int lo = 0, hi = 0;
    double mean = 0;
    stats(v, lo, hi, mean);
    cout << fixed << setprecision(2);
    cout << "min " << lo << " max " << hi << " mean " << mean << endl;
    return 0;
}

Lesson: References, overloading and default arguments →