返回多个值C++

Jac*_*aks 2 c++ variables return function

有没有办法从函数中返回多个值?在我正在研究的程序中,我希望将4个不同的int变量返回到main函数,从单独的函数返回,继续通过程序所需的所有统计数据.我发现没办法真正做到这一点.非常感谢任何帮助,谢谢.

jua*_*nza 7

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

struct foo
{
  int a, b, c, d;
};

foo bar() {
  return foo{1, 2, 3, 4};
}
Run Code Online (Sandbox Code Playgroud)

要么

std::tuple<int, int, int, int> bar() {
  return std::make_tuple(1,2,3,4);
}
Run Code Online (Sandbox Code Playgroud)

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

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


sfj*_*jac 7

使用C++ 11及更高版本,您可以使用std::tuplestd::tie编写非常符合Python语言风格的编程,例如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;
}
Run Code Online (Sandbox Code Playgroud)

如果你有C++ 14,这会变得更加清晰,因为你不需要声明返回类型bar:

auto bar() {
    return std::make_tuple(1,2,3,4);
}
Run Code Online (Sandbox Code Playgroud)