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

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


The only thing I can see is that your forcing a copy of the list you return. It would be more efficient to do something like:

  void DoSomething(const std::vector<SomeType>& in, std::vector<SomeType>& out)  {  ...  // no need to return anything, just modify out  }

Because you pass in the list you want to return, you avoid the extra copy.

Edit: This is an old reply. If you can use a modern C++ compiler with move semantics, you don't need to worry about this. Of course, this answer still applies if the object you are returning DOES NOT have move semantics.


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.


I'd use the generic approach:

template <typename InIt, typename OutIt>void DoMagic(InIt first, InIt last, OutIt out){  for(; first != last; ++first) {    if(IsCorrectIngredient(*first)) {      *out = DoMoreMagic(*first);      ++out;    }  }}

Now you can call it

std::vector<MagicIngredients> ingredients;std::vector<MagicResults> result;DoMagic(ingredients.begin(), ingredients.end(), std::back_inserter(results));

You can easily change containers used without changing the algorithm used, also it is efficient there's no overhead in returning containers.