Tamim Addari
Tamim Addari

Reputation: 7841

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

How to return a integer and a vector from a function. In c++11 I can use tuple. But I have to use C++98 standard.

problem is like this,

int myfunction(parameter 1,parameter 2)
{
   vector<int> created_here;
   //do something with created here
   return int & created_here both

}

How can I do that. By the way, I have to use my function recursively.So I have thought a way like this,

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; 

}

will this work? Or there is a better solution. and By the way, My actual problem is finding the solution of the travelling salesman problem.that should clarify my needs

Upvotes: 2

Views: 4111

Answers (3)

Saksham
Saksham

Reputation: 9390

It won't be a good choice to create a vector in your function and using it if you would be making recursive function calls.

I would suggest you to pass these 2 parameters by reference from your main function(rather than declaring it globally(as OP did) and manipulate them as you go calling the function recursively rather than returning them in each call.

Upvotes: 0

Tay Wee Wen
Tay Wee Wen

Reputation: 468

The best way is to use a data structure.

struct MyParam
{
    int myInt;
    vector<int> myVect;
} ;

MyParam myfunction( MyParam myParam )
{
    return myParam;
}

Upvotes: 2

orlp
orlp

Reputation: 117781

Use std::pair<>:

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

    return std::make_pair(i, v);
}

Upvotes: 6

Related Questions