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

前端 未结 9 1424
无人共我
无人共我 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:32

    I'd use something like

    std::auto_ptr<std::vector<int> > computeValues(int input);
    {
       std::auto_ptr<std::vector<int> > r(new std::vector<int>);
       r->push_back(...) // Hundreds of these
       return r;
    }
    

    No copying overhead in the return or risk of leaking (if you use auto_ptr correctly in the caller).

    0 讨论(0)
  • 2021-01-01 05:33

    One other option is boost::tuple: http://www.boost.org/doc/libs/1_38_0/libs/tuple/doc/tuple_users_guide.html

    int x, y;
    boost::tie(x,y) = bar();
    
    0 讨论(0)
  • 2021-01-01 05:38

    I'd say your new solution is more general, and better style. I'm not sure I'd worry too much about style in c++, more about usability and efficiency.

    If you're returning a lot of items, and know the size, using a vector would allow you to reserve the memory in one allocation, which may or may not be worth it.

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