从c++函数中返回多个值的首选方法是什么?例如,假设有一个函数对两个整数进行除法并同时返回商和余数。我经常看到的一种方法是使用引用形参:

void divide(int dividend, int divisor, int& quotient, int& remainder);

一种变体是返回一个值,并通过引用形参传递另一个值:

int divide(int dividend, int divisor, int& remainder);

另一种方法是声明一个结构体来包含所有的结果并返回:

struct divide_result {
    int quotient;
    int remainder;
};

divide_result divide(int dividend, int divisor);

这些方法中是否有一种通常是首选的,还是有其他的建议?

编辑:在实际代码中,可能会有两个以上的结果。它们也可能是不同类型的。


当前回答

在这里,我正在编写一个程序,在c++中返回多个值(超过两个值)。此程序在c++14 (g++ 4.9.2)中可执行。程序就像计算器。

#  include <tuple>
# include <iostream>

using namespace std; 

tuple < int,int,int,int,int >   cal(int n1, int n2)
{
    return  make_tuple(n1/n2,n1%n2,n1+n2,n1-n2,n1*n2);
}

int main()
{
    int qut,rer,add,sub,mul,a,b;
    cin>>a>>b;
    tie(qut,rer,add,sub,mul)=cal(a,b);
    cout << "quotient= "<<qut<<endl;
    cout << "remainder= "<<rer<<endl;
    cout << "addition= "<<add<<endl;
    cout << "subtraction= "<<sub<<endl;
    cout << "multiplication= "<<mul<<endl;
    return 0;
}

因此,您可以清楚地理解,通过这种方式,您可以从一个函数返回多个值。使用std::pair只能返回2个值,而std::tuple可以返回两个以上的值。

其他回答

在这里,我正在编写一个程序,在c++中返回多个值(超过两个值)。此程序在c++14 (g++ 4.9.2)中可执行。程序就像计算器。

#  include <tuple>
# include <iostream>

using namespace std; 

tuple < int,int,int,int,int >   cal(int n1, int n2)
{
    return  make_tuple(n1/n2,n1%n2,n1+n2,n1-n2,n1*n2);
}

int main()
{
    int qut,rer,add,sub,mul,a,b;
    cin>>a>>b;
    tie(qut,rer,add,sub,mul)=cal(a,b);
    cout << "quotient= "<<qut<<endl;
    cout << "remainder= "<<rer<<endl;
    cout << "addition= "<<add<<endl;
    cout << "subtraction= "<<sub<<endl;
    cout << "multiplication= "<<mul<<endl;
    return 0;
}

因此,您可以清楚地理解,通过这种方式,您可以从一个函数返回多个值。使用std::pair只能返回2个值,而std::tuple可以返回两个以上的值。

在C(以及c++)标准中,有使用div、ldiv(以及C99中的lldiv)函数从<stdlib.h>(或<cstdlib>)返回结构的先例。

“返回值和返回参数的混合”通常是最不干净的。

让函数返回状态并通过返回参数返回数据在C中是合理的;在c++中,你可以使用异常来传递失败信息,这就不那么明显了。

如果有两个以上的返回值,那么类结构的机制可能是最好的。

std::pair<int, int> divide(int dividend, int divisor)
{
   // :
   return std::make_pair(quotient, remainder);
}

std::pair<int, int> answer = divide(5,2);
 // answer.first == quotient
 // answer.second == remainder

Std::pair本质上是你的结构解决方案,但是已经为你定义好了,并且可以适应任何两种数据类型。

快速回答:

#include <iostream>
using namespace std;

// different values of [operate] can return different number.
int yourFunction(int a, int b, int operate)
{
    a = 1;
    b = 2;

    if (operate== 1)
    {
        return a;
    }
    else
    {
        return b;
    }
}

int main()
{
    int a, b;

    a = yourFunction(a, b, 1); // get return 1
    b = yourFunction(a, b, 2); // get return 2

    return 0;
}

对于返回两个值,我使用std::pair(通常是类型定义的)。您应该查看boost::tuple(在c++ 11及更新版本中,有std::tuple),以获得两个以上的返回结果。

随着c++ 17中结构化绑定的引入,返回std::tuple可能会成为可接受的标准。