Return 多值 C++

Return Multiple Values C++

有没有办法从一个函数中 return 多个值?在我正在处理的程序中,我希望 return 4 个不同的 int 变量到主函数,从一个单独的函数,所有需要继续执行程序的统计信息。我发现没有办法真正做到这一点。非常感谢任何帮助,谢谢。

C++ 不支持 return 多个值,但您可以 return 包含其他类型实例的类型的单个值。例如,

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 中,您将能够使用 结构化绑定 ,它允许您从 returning 表示多个类型的函数中初始化多个对象值:

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

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

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

一个解决方案可能是 return 来自函数的向量:

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

编辑:这个问题之前已经被问过,将其标记为重复。 Returning multiple values from a C++ function

编辑 #2 :我看到多个建议结构的答案,但我不明白为什么 "declaring a struct for a single function" 是相关的,因为它们显然是其他模式,比如 out 参数,用于解决这样的问题。

您可以使用将 4 int 秒作为参考的函数。

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)。为了完整性,我添加了这种方法。

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

#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 的 return 类型:

auto bar() {
    return std::make_tuple(1,2,3,4);
}