Returning multiple values from a C++ function

后端 未结 21 2523
别跟我提以往
别跟我提以往 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:40
    std::pair<int, int> divide(int dividend, int divisor)
    {
       // :
       return std::make_pair(quotient, remainder);
    }
    
    std::pair<int, int> answer = divide(5,2);
     // answer.first == quotient
     // answer.second == remainder
    

    std::pair is essentially your struct solution, but already defined for you, and ready to adapt to any two data types.

    0 讨论(0)
  • 2020-11-22 01:41

    I'd say there is no preferred method, it all depends on what you're going to do with the response. If the results are going to be used together in further processing then structures make sense, if not I'd tend to pass then as individual references unless the function was going to be used in a composite statement:

    x = divide( x, y, z ) + divide( a, b, c );

    I often choose to pass 'out structures' by reference in the parameter list rather than having the pass by copy overhead of returning a new structure (but this is sweating the small stuff).

    void divide(int dividend, int divisor, Answer &ans)

    Are out parameters confusing? A parameter sent as reference suggests the value is going to change (as opposed to a const reference). Sensible naming also removes confusion.

    0 讨论(0)
  • 2020-11-22 01:43

    Alternatives include arrays, generators, and inversion of control, but none is appropriate here.

    Some (e.g. Microsoft in historical Win32) tend to use reference parameters for simplicity, because it's clear who allocates and how it will look on the stack, reduces the proliferation of structures, and allows a separate return value for success.

    "Pure" programmers prefer the struct, assuming it is the function value (as is the case here), rather than something that's touched incidentally by the function. If you had a more complicated procedure, or something with state, you'd probably use references (assuming you have a reason for not using a class).

    0 讨论(0)
  • 2020-11-22 01:45

    It's entirely dependent upon the actual function and the meaning of the multiple values, and their sizes:

    • If they're related as in your fraction example, then I'd go with a struct or class instance.
    • If they're not really related and can't be grouped into a class/struct then perhaps you should refactor your method into two.
    • Depending upon the in-memory size of the values you're returning, you may want to return a pointer to a class instance or struct, or use reference parameters.
    0 讨论(0)
  • 2020-11-22 01:46

    In C++11 you can:

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

    In C++17:

    #include <tuple>
    
    std::tuple<int, int> divide(int dividend, int divisor) {
        return  {dividend / divisor, dividend % divisor};
    }
    
    #include <iostream>
    
    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 <iostream>
    
    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;
    }
    
    0 讨论(0)
  • 2020-11-22 01:48

    The OO solution for this is to create a ratio class. It wouldn't take any extra code (would save some), would be significantly cleaner/clearer, and would give you some extra refactorings letting you clean up code outside this class as well.

    Actually I think someone recommended returning a structure, which is close enough but hides the intent that this needs to be a fully thought-out class with constructor and a few methods, in fact, the "method" that you originally mentioned (as returning the pair) should most likely be a member of this class returning an instance of itself.

    I know your example was just an "Example", but the fact is that unless your function is doing way more than any function should be doing, if you want it to return multiple values you are almost certainly missing an object.

    Don't be afraid to create these tiny classes to do little pieces of work--that's the magic of OO--you end up breaking it down until every method is very small and simple and every class small and understandable.

    Another thing that should have been an indicator that something was wrong: in OO you have essentially no data--OO isn't about passing around data, a class needs to manage and manipulate it's own data internally, any data passing (including accessors) is a sign that you may need to rethink something..

    0 讨论(0)
提交回复
热议问题