【发布时间】:2012-02-08 15:39:19
【问题描述】:
int DFS(a, b,c,d)
{
first=a+b;
second=c+d;
return(first,second);
}
solution, cost_limit = DFS(a, b,c,d);
我可以这样做吗?如何?
【问题讨论】:
-
很不清楚你在这里问什么。我建议您解释一下分配的含义以及变量的含义。
标签: c++
int DFS(a, b,c,d)
{
first=a+b;
second=c+d;
return(first,second);
}
solution, cost_limit = DFS(a, b,c,d);
我可以这样做吗?如何?
【问题讨论】:
标签: c++
您可以通过两种方式做到这一点:
创建一个具有两个值的结构并返回它:
struct result
{
int first;
int second;
};
struct result DFS(a, b, c, d)
{
// code
}
输出参数:
void DFS(a, b, c, d, int& first, int& second)
{
// assigning first and second will be visible outside
}
致电:
DFS(a, b, c, d, first, second);
【讨论】:
solution = first; cost_limit = second;
在 C++11 中,您可以使用元组类型和 tie。
#include <tuple>
std::tuple<int, int> DFS (int a, int b, int c, int d)
{
return std::make_tuple(a + b, c + d);
}
...
int solution, cost_limit;
std::tie(solution, cost_limit) = DFS(a, b, c, d);
【讨论】:
std::pair<int, int>
tie,所以它看起来很丑:std::pair<int, int> result = DFS(a,b,c,d); solution = result.first; cost_limit = result.second;。
tie)
您应该知道的一件事是,如果 a,b,c,d 不是基类型,而是您定义的类的实例,比如 Foo,并且您重载了该类的 = 运算符,则必须确保事实上,运算符将返回对已分配对象的引用,否则您将无法链接分配(solution = cost_limit = DFS(..) 只会分配给 cost_limit)。 = 运算符应如下所示:
Foo& Foo::operator =(const Foo& other)
{
//do stuff
return other;
}
【讨论】:
如果不能使用 C++11,则可以使用引用。
通过在参数中传递对变量的引用。
int DFS(int a, int b, int c, int d, int &cost_limit)
{
cost_limit = c + d;
return a + b;
}
int solution, cost_limit;
solution = DFS(a, b, c, d, cost_limit);
【讨论】:
使用 C++17,您可以解包一对或元组
auto[i, j] = pair<int, int>{1, 2};
cout << i << j << endl; //prints 12
auto[l, m, n] = tuple<int, int, int>{1, 2, 3};
cout << l << m << n << endl; //prints 123
【讨论】:
<int, int> 顺便说一句:stackoverflow.com/questions/9270563/…