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

294

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

If you want to be really hardcore, you could use boost::tuple.

tuple<int, int, double> add_multiply_divide(int a, int b) {
  return make_tuple(a+b, a*b, double(a)/double(b));
}

But since it seems all your objects are of a single, non-polymorphic type, then the std::vector is all well and fine. If your types were polymorphic (inherited classes of a base class) then you'd need a vector of pointers, and you'd need to remember to delete all the allocated objects before throwing away your vector.

Solution 5

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.

Share:
294
fallaway
Author by

fallaway

Updated on July 09, 2022

Comments

  • fallaway
    fallaway almost 2 years

    Here is my program:

    package main
    
    import (
        "fmt"
    )
    
    type Number struct {
        val int
    }
    
    func (num * Number) Increment () {
        num.val += 1
    }
    
    func (num Number) Value() int {
        return num.val
    }
    
    func main() {
        numbers := []Number {
            {val: 12}, 
            {val: 7},
            {val: 0},
        }
    
        for _, each := range numbers {
            each.Increment()
            fmt.Println(each.Value())
        }
    
        for _, each := range numbers {
            fmt.Println(each.Value())
        }
    }
    

    Here is the output:

    13
    8
    1
    12
    7
    0
    

    First question: why does the Increment()method not update the value in the first for loop? I used pointer as the receiver so that val can be updated for sure, but why would the second for loop print out the original values of those Numbers?

    Second question: what can be done so that when I iterate over a slice of Numbers and invoke the Increment() method, all Numbers are correctly incremented?

    [Edit] I noticed that if I use index-based for loop and invoke the Increment() method, values will be correctly updated. Why?

    for i := 0; i < len(numbers); i++ {
        numbers[i].Increment()
    }