How do I return hundreds of values from a C++ function?

前端 未结 9 1466
无人共我
无人共我 2021-01-01 04:37

In C++, whenever a function creates many (hundreds or thousands of) values, I used to have the caller pass an array that my function then fills with the output values:

9条回答
  •  悲&欢浪女
    2021-01-01 05:24

    Response to Edit: Well, if you need to return hundreds and thousands if values, a tuple of course would not be the way to go. Best pick the solution with the iterator then, but it's best not use any specific iterator type.


    If you use iterators, you should use them as generic as possible. In your function you have used an insert iterator like insert_iterator< vector >. You lost any genericity. Do it like this:

    template
    void computeValues(int input, OutputIterator output) {
        ...
    }
    

    Whatever you give it, it will work now. But it will not work if you have different types in the return set. You can use a tuple then. Also available as std::tuple in the next C++ Standard:

    boost::tuple computeValues(int input) { 
        ....
    }
    

    If the amount of values is variadic and the type of the values is from a fixed set, like (int, bool, char), you can look into a container of boost::variant. This however implies changes only on the call-side. You can keep the iterator style of above:

    std::vector< boost::variant > data;
    computeValues(42, std::back_inserter(data));
    

提交回复
热议问题