Best way to return list of objects in C++?

前端 未结 6 2098
眼角桃花
眼角桃花 2021-02-12 08:56

It\'s been a while since I programmed in C++, and after coming from python, I feel soooo in a straight jacket, ok I\'m not gonna rant.

I have a couple of functions that

6条回答
  •  南笙
    南笙 (楼主)
    2021-02-12 09:19

    If you really need a new list, I would simply return it. Return value optimization will take care of no needless copies in most cases, and your code stays very clear.
    That being said, taking lists and returning other lists is indeed python programming in C++.

    A, for C++, more suitable paradigm would be to create functions that take a range of iterators and alter the underlying collection.

    e.g.

    void DoSomething(iterator const & from, iterator const & to);
    

    (with iterator possibly being a template, depending on your needs)

    Chaining operations is then a matter of calling consecutive methods on begin(), end(). If you don't want to alter the input, you'd make a copy yourself first.

    std::vector theOutput(inputVector);
    

    This all comes from the C++ "don't pay for what you don't need" philosophy, you'd only create copies where you actually want to keep the originals.

提交回复
热议问题