Returning multiple values from a C++ function

后端 未结 21 2505
别跟我提以往
别跟我提以往 2020-11-22 01:04

Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the rema

相关标签:
21条回答
  • 2020-11-22 01:55

    rather than returning multiple values,just return one of them and make a reference of others in the required function for eg:

    int divide(int a,int b,int quo,int &rem)
    
    0 讨论(0)
  • 2020-11-22 01:56

    Boost tuple would be my preferred choice for a generalized system of returning more than one value from a function.

    Possible example:

    include "boost/tuple/tuple.hpp"
    
    tuple <int,int> divide( int dividend,int divisor ) 
    
    {
      return make_tuple(dividend / divisor,dividend % divisor )
    }
    
    0 讨论(0)
  • 2020-11-22 01:56

    Quick answer:

    #include <iostream>
    using namespace std;
    
    // different values of [operate] can return different number.
    int yourFunction(int a, int b, int operate)
    {
        a = 1;
        b = 2;
    
        if (operate== 1)
        {
            return a;
        }
        else
        {
            return b;
        }
    }
    
    int main()
    {
        int a, b;
    
        a = yourFunction(a, b, 1); // get return 1
        b = yourFunction(a, b, 2); // get return 2
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题