如何在C++中从函数返回两个值

How to return two values from a function in C++?

本文关键字:两个 返回 函数 C++      更新时间:2023-10-16

如何从函数返回整数和向量。在 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; 
}

这行得通吗?或者有更好的解决方案。顺便说一下,我的实际问题是找到旅行推销员问题的解决方案,这应该澄清我的需求<</p>

div class="answers">

使用std::pair<>

std::pair<int, std::vector<int> > myfunction() {
    int i;
    std::vector<int> v;
    return std::make_pair(i, v);
}

最好的方法是使用数据结构。

struct MyParam
{
    int myInt;
    vector<int> myVect;
} ;
MyParam myfunction( MyParam myParam )
{
    return myParam;
}

在函数中创建向量并在进行递归函数调用时使用它将不是一个好的选择。

我建议您通过引用从主函数传递这两个参数(而不是全局声明它(如 OP 所做的那样),并在您递归调用函数时操作它们,而不是在每次调用中返回它们。