Hi,

Below is the first exercise on struct that I did. I have a feeling that I didn't get an idea behind the struct. Looking at the program I wrote, I am wondering what is the benefit of writing this program using struct. I could have write 5 functions for mean, median, smallest, largest, and call each of them when printing the results. The exercise asks me to create a struct, so it must imply that there's some benefit from using struct. I'm suspecting that I didn't get the idea... Could you please suggest some improvement? Thanks a lot...

Code:
// Exercise 8.12
#include "std_lib_facilities.h"
/*
	Write a function that finds the smallest & the largest element of a vector
	argument and also compute the mean and the median. Do not use global variables.
	Either return a struct containing results or pass them back through reference
	arguments. Which of the 2 ways of returning several result values do you prefer and why?

*/

struct stats {
	vector<double> v;
	double smallest, largest, median;
	double fmean(vector<double>& v);
	double fmedian(vector<double>& v);
	double fsmallest(vector<double>& v);
	double flargest(vector<double>& v);
};

int main()
try {
	stats mystats;
	vector<double> v;
	double x;
	cout << "Enter some elements for a vector: \n";
	while (cin >> x)
		v.push_back(x);
	cout << "Here are some summary statistics: \n";
	cout << "Smallest: " << mystats.fsmallest(v) << '\n';
	cout << "Largest: " << mystats.flargest(v) << '\n';
	cout << "Mean: " << mystats.fmean(v) << '\n';
	cout << "Median: " << mystats.fmedian(v) << '\n';
	
}
catch (runtime_error e) {
	cout << e.what();
}

double stats::fsmallest(vector<double>& v)
{
	smallest = v[0];
	for (unsigned int i = 0; i < v.size(); ++i) {
		if (v[i] < smallest)
			smallest = v[i];
	}
	return smallest;
}

double stats::flargest(vector<double>& v)
{
	largest = v[0];
	for (unsigned int i = 0; i < v.size(); ++i) {
		if (v[i] > largest)
			largest = v[i];
	}
	return largest;
}

double stats::fmean(vector<double>& v)
{
	double sum = 0;
	for (unsigned int i = 0; i < v.size(); ++i) {
		sum += v[i];
	}
	return sum / v.size();
}

double stats:: fmedian(vector<double>& v)
{
	sort(v.begin(), v.end());
	median = 0;
	for (unsigned int i = 0; i < v.size(); ++i) {
		if (v.size()%2==0)
			median = (v[v.size()/2] + v[v.size()/2-1])/2;
		else
			median = v[v.size()/2];	
	}
	return median;
}