I'm new to programming and I'm studying the C++ programming language using the book : Programming principles and practice using C++. I'm here today because at the end of chapter 8, the author focuses on functions and proposes an exercise to invite the learner to think about the better solution to a problem :
Write a function that finds the smallest and the largest element of a vector argument and also computes the mean and the median. Do not use global variables. Either return a
structcontaining the results or pass them back through reference arguments. Which of the two was of returning several values do you prefer and why ?
Now, usually I wouldn't define a single function to perform several actions but in this case I have to create just one function and think about how to return several values. My first approach was to create a function that takes reference arguments like this :
void my_func(
vector<double>& numbers,
double& min,
double& max,
double& mean,
double& median
);
But going on with writing the program I started to think that this solution used too many arguments and maybe the other solution proposed (using struct) would be better. How would you use a struct to solve this problem ? How do you return several values from a function ?
Using struct for this problem is simple: define a struct for the return type, and use it, like this:
struct stats {
double min;
double max;
double mean;
double median;
};
stats my_func(vector<double>& numbers) {
stats res;
...
res.min = ...
res.max = ...
res.mean = ...
res.median = ...
return res;
}
The tradeoff here is that in exchange for having a much simpler function signature, the users of your function need to extract the elements that they want one by one.
But what about if the struct is really complex and the cost of copying becomes too expensive?
It takes a structure of extreme size for copying to become too expensive in comparison to the "payload" CPU time of your function. On top of that, C++ optimizer reduces the copying costs by employing copy elision and return value optimization strategies when you do this:
stats s = my_func(numbers);
When the struct becomes so gigantic that you don't want to copy it, combine the two approaches like this:
void my_func(vector<double>& numbers, stats& res);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With