从C ++函数返回多个值 [英] Returning multiple values from a C++ function
问题描述
是否有从C ++函数返回多个值的首选方法?例如,假设一个函数将两个整数相除,并返回商和余数。我通常看到的一种方法是使用参考参数:
Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters:
void divide(int dividend, int divisor, int& quotient, int& remainder);
变体是返回一个值,并通过引用参数传递另一个值:
A variation is to return one value and pass the other through a reference parameter:
int divide(int dividend, int divisor, int& remainder);
另一种方法是声明一个结构来包含所有结果,并返回:
Another way would be to declare a struct to contain all of the results and return that:
struct divide_result {
int quotient;
int remainder;
};
divide_result divide(int dividend, int divisor);
这些方法之一通常是首选还是有其他建议?
Is one of these ways generally preferred, or are there other suggestions?
编辑:在现实世界的代码中,可能有两个以上的结果。
In the real-world code, there may be more than two results. They may also be of different types.
推荐答案
对于返回两个值,我使用 std :: pair
(通常typedef'd)。你应该看看 boost :: tuple
(在C ++ 11和更新版本中,有 std :: tuple
)超过两个返回结果。
For returning two values I use a std::pair
(usually typedef'd). You should look at boost::tuple
(in C++11 and newer, there's std::tuple
) for more than two return results.
这篇关于从C ++函数返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!