Get two results from one function.
What to build
A function with one read-only input and two outputs.
Requirements
- Write
void min_max(const vector<int>& v, int& low, int& high). - Print
min L max H.
Input
The first line has n. The second line has n whole numbers.
Output
One line.
Constraints
n is from 1 to 1000.
Example
Input:
4
3 9 2 7
Output:
min 2 max 9
Why it works
const& avoids copying the list and protects it, while the plain references give the function somewhere to put its results.
Examples
Example 1 · Input
4 3 9 2 7
Expected output
min 2 max 9
Example 2 · Input
1 5
Expected output
min 5 max 5
Hints
Hint 1
Take the vector by const reference.
Hint 2
Take low and high by plain reference.
Hint 3
Start both from the first element.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;
void min_max(const vector<int>& v, int& low, int& high) {
low = v[0];
high = v[0];
for (int x : v) {
if (x < low) low = x;
if (x > high) high = x;
}
}
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
int low = 0, high = 0;
min_max(v, low, high);
cout << "min " << low << " max " << high << endl;
return 0;
}