如何从函数返回整数和向量。在c ++ 11中,我可以使用元组。但我必须使用C ++ 98标准。
问题是这样的,
int myfunction(parameter 1,parameter 2)
{
vector<int> created_here;
//do something with created here
return int & created_here both
}
我该怎么做?顺便说一下,我必须递归地使用我的函数。所以 我想过像这样的方式,
int n;
vector<int> A;
int myfunction(int pos,int mask_cities,vector<int> &A)
{
if(mask = (1<<n)-1)
return 0;
vector<int> created_here;
int ans = 999999;
for(int i=0;i<n;++i){
int tmp = myfunction(pos+1,mask|1<<i,created_here);
if(tmp<ans){
A = created_here;
ans = tmp;
}
}
return ans;
}
这会有效吗?或者有一个更好的解决方案。
顺便说一句,我的实际问题是找到旅行商问题的解决方案。这应该澄清我的需求
答案 0 :(得分:6)
使用std::pair<>
:
std::pair<int, std::vector<int> > myfunction() {
int i;
std::vector<int> v;
return std::make_pair(i, v);
}
答案 1 :(得分:2)
最好的方法是使用数据结构。
struct MyParam
{
int myInt;
vector<int> myVect;
} ;
MyParam myfunction( MyParam myParam )
{
return myParam;
}
答案 2 :(得分:0)
如果要进行递归函数调用,在函数中创建向量并使用它不是一个好的选择。
我建议你通过引用从main函数传递这两个参数(而不是全局声明它(如OP所做的那样)并在你递归调用函数时操纵它们,而不是在每次调用中返回它们。