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

前端 未结 6 2095
眼角桃花
眼角桃花 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:32

    Using a std::vector is the preferably way in many situations. Its guaranteed to use consecutive memory and is therefor pleasant for the L1 cache.

    You should be aware of what happends when your return type is std::vector. What happens under the hood is that the std::vector is recursive copied, so if SomeType's copy constructor is expensive the "return statement" may be a lengthy and time consuming operation.

    If you are searching and inserting a lot in your list you could look at std::set to get logarithmic time complexity instead of linear. (std::vectors insert is constant until its capacity is exceeded).

    You are saying that you have many "pipe functions"... sounds like an excellent scenario for std::transform.

提交回复
热议问题