我是编程新手,我正在使用这本书学习 C++ 编程语言:编程原则和使用 C++ 的实践。我今天来到这里是因为在第 8 章的结尾,作者将重点放在功能上并提出了一个练习,邀请学习者思考问题的更好解决方案:
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
struct
containing the results or pass them back through reference arguments. Which of the two was of returning several values do you prefer and why ?
现在,通常我不会定义一个函数来执行多个操作,但在这种情况下,我必须只创建一个函数并考虑如何返回多个值。我的第一种方法是创建一个函数,它接受这样的引用参数:
void my_func(
vector<double>& numbers,
double& min,
double& max,
double& mean,
double& median
);
但是继续编写程序,我开始认为这个解决方案使用了太多参数,也许建议的其他解决方案(使用 struct
)会更好。您将如何使用 struct
来解决这个问题?如何从一个函数返回多个值?
最佳答案
使用 struct
解决这个问题很简单:为返回类型定义一个 struct
,然后使用它,如下所示:
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;
}
这里的权衡是,为了换取更简单的函数签名,函数的用户需要一个一个地提取他们想要的元素。
But what about if the struct is really complex and the cost of copying becomes too expensive?
与函数的“有效负载”CPU 时间相比,复制变得过于昂贵需要一个极端大小的结构。最重要的是,C++ 优化器通过使用 copy elision 降低了复制成本。和 return value optimization执行此操作时的策略:
stats s = my_func(numbers);
当 struct
变得如此巨大以至于您不想复制它时,可以像这样结合这两种方法:
void my_func(vector<double>& numbers, stats& res);
关于c++ - 从函数返回值 : reference vs struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32478007/