user3235674
user3235674

Reputation:

Declaration of function to generate vector of class with a vector of another class

I have 2 classes:

class Item;
class Component;

And I have a function to generate a vector of Items from a vector of Components

static vector<Item> generateItemsFromComponents( vector<Component> components )
{
    vector<Item> vi;
    // ...
    return vi;
}

My question is, where do I declare this function? In the Item class or in the Component class? Or the class design is wrong? Maybe suggest better methods to achieve this?

Upvotes: 0

Views: 70

Answers (1)

quantdev
quantdev

Reputation: 23803

First, if there is a 1 to 1 conversion function from a Component to an Item, you should consider :

  • Having an explicit conversion method in Component, e.g. Item ToItem();, or
  • Having an implicit conversion operator, but this is unlikely unless automatic conversion (by the compiler) would make sense in any case.

e.g :

 operator const Item&() const;

Once you have the single conversion function available, the method that operates on containers does not really belong to any of your existing interfaces (unless you have a class for containers of Components already), so it makes sense to declare a free function :

Example:

vector<Item> generateItemsFromComponents( const vector<Component>& components )
{
    vector<Item> vi;
    for(auto& comp in components)
       vi.push_back(comp.ToItem());
    return vi;
}

However, as pointed by @chris, using std::transform directly, together with a lambda, makes things easier:

Example:

vector<Item> vi;
transform(begin(comp), end(comp), back_inserter(vi), [](Component c){ return c.ToItem(); }

The advantages of this last method:

  1. You are not dependent on the container type : you operate on iterators, comp could be any standard compliant container, not just a vector.
  2. It might be more efficient, and is definitely very readable

Answer:

  • Provide a single conversion function in the Component class
  • Use the standard <algorithm> together with this function
  • Consider lambdas as a substitute for very simple functions
  • If a function is not related to a type, just make it a free function

Upvotes: 1

Related Questions