试图返回多个值

时间:2009-07-10 03:51:59

标签: c++

我在此程序中返回多个值时遇到一些问题,这些值会计算min,max,mean,median。我做的第一件事是传递引用参数,它起作用了 - 但我读到创建一个结构或类是返回多个值的首选方法。

所以我尝试过,但是我没能取得好成绩。这是我到目前为止所做的。

#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();
}

显然,计算函数中的变量是未声明的。我只是不确定如何以正确的方式实现它以返回正确的值。到目前为止,我已经尝试过的东西,我已经得到了很好的解释。任何帮助将不胜感激 - 谢谢。

P.S。我已经查看了有关此主题的其他主题,我仍然感到困惑,因为需要传递给calculate()的参数与maxv结构中的变量之间没有任何差异。

1 个答案:

答案 0 :(得分:8)

有三种方法可以做到。

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;
     }
};