当一个函数需要返回两个参数时,您可以使用std::对编写它:
std::pair<int, int> f()
{return std::make_pair(1,2);}如果你想使用它,你可以这样写:
int one, two;
std::tie(one, two) = f();这种方法的问题是,您需要定义“一”和“二”,然后将它们赋给f()的返回值。如果我们能写一些像这样的东西,那会更好
auto {one, two} = f();我看了一次讲座(我不记得是哪一次了,对不起),演讲者说C++标准的人正在尝试做这样的事情。我想这篇演讲是两年前的。有没有人知道现在(几乎在c++17中)你能不能做到这一点,或者类似的事情?
发布于 2017-08-31 22:43:55
是的,有一种叫做structured bindings的东西,它允许以这种方式初始化多个值。
但是,语法使用square brackets:
#include <utility>
std::pair<int, int> f()
{
//return std::make_pair(1, 2); // also works, but more verbose
return { 1, 2 };
}
int main()
{
auto[one, two] = f();
}demo
https://stackoverflow.com/questions/45984214
复制相似问题