C++返回多个值

Return Multiple Values C++

本文关键字:返回 C++      更新时间:2023-10-16

有没有办法从一个函数返回多个值?在我正在处理的程序中,我希望将 4 个不同的 int 变量返回给主函数,从一个单独的函数,继续通过程序所需的所有统计信息。我找不到真正做到这一点的方法。任何帮助将不胜感激,谢谢。

对于 C++11 及更高版本,您可以使用 std::tuplestd::tie 进行非常符合 Python 返回多个值等语言风格的编程。例如:

#include <iostream>
#include <tuple>
std::tuple<int, int, int, int> bar() {
    return std::make_tuple(1,2,3,4);
}
int main() {
    int a, b, c, d;
    std::tie(a, b, c, d) = bar();
    std::cout << "[" << a << ", " << b << ", " << c << ", " << d << "]" << std::endl;
    return 0;
}

如果您有 C++14,这会变得更干净,因为您不需要声明 bar 的返回类型:

auto bar() {
    return std::make_tuple(1,2,3,4);
}
C++不支持

返回多个值,但您可以返回包含其他类型的实例的类型的单个值。例如

struct foo
{
  int a, b, c, d;
};
foo bar() {
  return foo{1, 2, 3, 4};
}

std::tuple<int, int, int, int> bar() {
  return std::make_tuple(1,2,3,4);
}

或者,在 C++17 中,您将能够使用结构化绑定,它允许您从返回表示多个值的类型的函数初始化多个对象:

// C++17 proposal: structured bindings
auto [a, b, c, d] = bar(); // a, b, c, d are int in this example

一种解决方案是从函数返回一个向量:

std::vector<int> myFunction()
{
   std::vector<int> myVector;
   ...
   return myVector;
}

另一种解决方案是添加参数:

int myFunction(int *p_returnValue1, int *p_returnValue2, int *p_returnValue3)
{
   *p_var1 = ...;
   *p_var2 = ...;
   *p_var3 = ...;
   return ...;
}

在第二个示例中,您需要声明将包含代码的四个结果的四个变量。

int value1, value2, value3, value4;

之后,调用函数,将每个变量的地址作为参数传递。

value4 = myFunction(&value1, &value2, &value3);

编辑:这个问题之前已经问过,将其标记为重复。从C++函数返回多个值

编辑#2:我看到多个答案建议结构,但我不明白为什么"为单个函数声明结构"是相关的,因为显然有其他模式,例如用于此类问题的参数。

如果您希望 top 返回的所有变量的类型都相同,您可以只返回它们的数组:

std::array<int, 4> fun() {
    std::array<int,4> ret;
    ret[0] = valueForFirstInt;
    // Same for the other three
    return ret;
}

您可以使用一个需要 4 int s 作为引用的函数。

void foo(int& a, int& b, int& c, int& d)
{
    // Do something with the ints
    return;
}

然后像使用它一样

int a, b, c, d;
foo(a, b, c, d);
// Do something now that a, b, c, d have the values you want

但是,对于这种特殊情况(4 个整数),我建议@juanchopanza的答案(std::tuple)。为了完整起见,我添加了此方法。