【问题标题】:Trying to return multiple values尝试返回多个值
【发布时间】:2010-11-09 14:32:27
【问题描述】:

我在这个计算最小值、最大值、平均值、中位数的程序中返回多个值时遇到了一些问题。我做的第一件事是传递引用参数,它起作用了——但我读到创建结构或类是返回多个值的首选方法。

所以我尝试了,但我没能得到好的结果。这是我到目前为止所得到的。

#include "std_lib_facilities.h"
struct maxv{
       int min_value;
       int max_value;
       double mean;
       int median;
};

maxv calculate(vector<int>& max)
{

    sort(max.begin(), max.end());

    min_value = max[0];

    int m = 0;
    m = (max.size()-1);
    max_value = max[m];

    for(int i = 0; i < max.size(); ++i) mean += max[i];
    mean = (mean/(max.size()));

    int med = 0;
    if((max.size())%2 == 0) median = 0;
    else
    {
        med = (max.size())/2;
        median = max[med];
        }

}

int main()
{
    vector<int>numbers;
    cout << "Input numbers. Press enter, 0, enter to finish.\n";
    int number;
    while(number != 0){
                 cin >> number;
                 numbers.push_back(number);}
    vector<int>::iterator i = (numbers.end()-1);
    numbers.erase(i);
    maxv result = calculate(numbers);
    cout << "MIN: " << result.min_value << endl;
    cout << "MAX: " << result.max_value << endl;
    cout << "MEAN: " << result.mean << endl;
    cout << "MEDIAN: " << result.median << endl;
    keep_window_open();
}

显然计算函数中的变量是未声明的。我只是不确定如何以正确的方式实现这一点以返回正确的值。到目前为止,从我尝试过的事情来看,我已经得到了非常明确的价值观。任何帮助将不胜感激 - 谢谢。

附:我已经查看了有关此主题的其他线程,但我仍然有点困惑,因为需要传递给 calculate() 的参数和 maxv 结构中的变量之间没有任何区别。

【问题讨论】:

  • 为什么不展示完整的功能呢?由于您没有将均值初始化为零,因此可能会错误计算中位数。
  • 很高兴地说“这是我目前所拥有的”。

标签: c++


【解决方案1】:

有三种方法可以做到这一点。

1) 从计算函数返回一个 maxv 实例

maxv calculate(vector<int>& max)
{
    maxv rc; //return code
    ... some calculations ...
    ... initialize the instance which we are about to return ...
    rc.min_value = something;
    rc.max_value = something else;
    ... return it ...
    return rc;
 }

2) 通过引用传入一个 maxv 实例

void calculate(vector<int>& max, maxv& rc)
{
    ... some calculations ...
    ... initialize the instance which we were passed as a parameter ...
    rc.min_value = something;
    rc.max_value = something else;
 }

3) 说 calculate 是 maxv 结构体的方法(或者更好的是构造函数)

struct maxv
{
    int min_value;
    int max_value;
    double mean;
    int median;

    //constructor
    maxv(vector<int>& max)
    {
        ... some calculations ...
        ... initialize self (this instance) ...
        this->min_value = something;
        this->max_value = something else;
     }
};

【讨论】:

  • 第三个选项特别好,因为它允许通过引用传递值,但避免了动态内存分配的任何问题。它也是面向对象且干净的。好主意。
  • 非常感谢这是完美的。
猜你喜欢
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
相关资源
最近更新 更多