从 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++ 17 中结构化绑定的引入,返回 std::tuple
应该成为公认的标准.
With introduction of structured binding in C++ 17, returning std::tuple
should probably become accepted standard.
这篇关于从 C++ 函数返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!