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)
使用C++ 11及更高版本,您可以使用std::tuple和std::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)