Returning multiple values from a C++ function

后端 未结 21 2868
别跟我提以往
别跟我提以往 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:46

    In C++11 you can:

    #include 
    
    std::tuple divide(int dividend, int divisor) {
        return  std::make_tuple(dividend / divisor, dividend % divisor);
    }
    
    #include 
    
    int main() {
        using namespace std;
    
        int quotient, remainder;
    
        tie(quotient, remainder) = divide(14, 3);
    
        cout << quotient << ',' << remainder << endl;
    }
    

    In C++17:

    #include 
    
    std::tuple divide(int dividend, int divisor) {
        return  {dividend / divisor, dividend % divisor};
    }
    
    #include 
    
    int main() {
        using namespace std;
    
        auto [quotient, remainder] = divide(14, 3);
    
        cout << quotient << ',' << remainder << endl;
    }
    

    or with structs:

    auto divide(int dividend, int divisor) {
        struct result {int quotient; int remainder;};
        return result {dividend / divisor, dividend % divisor};
    }
    
    #include 
    
    int main() {
        using namespace std;
    
        auto result = divide(14, 3);
    
        cout << result.quotient << ',' << result.remainder << endl;
    
        // or
    
        auto [quotient, remainder] = divide(14, 3);
    
        cout << quotient << ',' << remainder << endl;
    }
    

提交回复
热议问题